[LeetCode] Paint Fence 粉刷篱笆

简介:

There is a fence with n posts, each post can be painted with one of the k colors.

You have to paint all the posts such that no more than two adjacent fence posts have the same color.

Return the total number of ways you can paint the fence.

Note:
n and k are non-negative integers.

这道题让我们粉刷篱笆,有n个部分需要刷,有k种颜色的油漆,规定了不能有超过两个的相同颜色涂的部分,问我们总共有多少种刷法。那么我们首先来分析一下,如果n=0的话,说明没有需要刷的部分,直接返回0即可,如果n为1的话,那么有几种颜色,就有几种刷法,所以应该返回k,当n=2时,k=2时,我们可以分两种情况来统计,一种是相邻部分没有相同的,一种相同部分有相同的颜色,那么对于没有相同的,对于第一个格子,我们有k种填法,对于下一个相邻的格子,由于不能相同,所以我们只有k-1种填法。而有相同部分颜色的刷法和上一个格子的不同颜色刷法相同,因为我们下一格的颜色和之前那个格子颜色刷成一样的即可,最后总共的刷法就是把不同和相同两个刷法加起来,参见代码如下:

解法一:

class Solution {
public:
    int numWays(int n, int k) {
        if (n == 0) return 0;
        int same = 0, diff = k;
        for (int i = 2; i <= n; ++i) {
            int t = diff;
            diff = (same + diff) * (k - 1);
            same = t;
        }
        return same + diff;
    }
};

下面这种解法和上面那方法几乎一样,只不过多了一个变量,参见代码如下:

解法二:

class Solution {
public:
    int numWays(int n, int k) {
        if (n == 0) return 0;
        int same = 0, diff = k, res = same + diff;
        for (int i = 2; i <= n; ++i) {
            same = diff;
            diff = res * (k - 1);
            res = same + diff;
        }
        return res;
    }
};

本文转自博客园Grandyang的博客,原文链接:粉刷篱笆[LeetCode] Paint Fence ,如需转载请自行联系原博主。

相关文章
[LeetCode] Paint Fence
Problem Description: There is a fence with n posts, each post can be painted with one of the k colors.
712 0
|
C++
[LeetCode] Paint House
Problem Description: There are a row of n houses, each house can be painted with one of the three colors: red, blue or green.
1193 0
|
4天前
|
算法 C++
【刷题】Leetcode 1609.奇偶树
这道题是我目前做过最难的题,虽然没有一遍做出来,但是参考大佬的代码,慢慢啃的感觉的真的很好。刷题继续!!!!!!
7 0
|
4天前
|
算法 索引
【刷题】滑动窗口精通 — Leetcode 30. 串联所有单词的子串 | Leetcode 76. 最小覆盖子串
经过这两道题目的书写,相信大家一定深刻认识到了滑动窗口的使用方法!!! 下面请大家继续刷题吧!!!
8 0
|
4天前
|
算法
【刷题】 leetcode 面试题 08.05.递归乘法
递归算法是一种在计算机科学和数学中广泛应用的解决问题的方法,其基本思想是利用问题的自我相似性,即将一个大问题分解为一个或多个相同或相似的小问题来解决。递归算法的核心在于函数(或过程)能够直接或间接地调用自身来求解问题的不同部分,直到达到基本情况(也称为基础案例或终止条件),这时可以直接得出答案而不必再进行递归调用。
21 4
【刷题】 leetcode 面试题 08.05.递归乘法
|
4天前
|
存储 算法 安全
【刷题】 leetcode 面试题 01.06 字符串压缩
来看效果: 非常好!!!过啦!!!
25 5
【刷题】 leetcode 面试题 01.06 字符串压缩
|
4天前
|
存储 算法 测试技术