[LintCode] 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.

Notice

n and k are non-negative integers.

Example
Given n=3, k=2 return 6

post 1, post 2, post 3
way1 0 0 1 
way2 0 1 0
way3 0 1 1
way4 1 0 0
way5 1 0 1
way6 1 1 0

LeetCode上的原题,请参见我之前的博客Paint Fence

class Solution {
public:
    /**
     * @param n non-negative integer, n posts
     * @param k non-negative integer, k colors
     * @return an integer, the total number of ways
     */
    int numWays(int n, int k) {
        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;
    }
};

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

相关文章
|
8月前
light oj 1231-1232 - 1233- Coin Change 背包
暂时到半懂不懂也没办法讲明白,就不误人子弟了,直接贴代码了。
23 0
Codeforces1486 A Shifting Stacks (开long long)
Codeforces1486 A Shifting Stacks (开long long)
57 0
|
人工智能
Codeforces 220B-Little Elephant and Array-扫描线 & 树状数组
题意: 给出一个长度为n的数组,有m个询问,每次询问给出一个区间,问这个区间内有多少个数x恰好出现x次
107 0
Codeforces 220B-Little Elephant and Array-扫描线 & 树状数组
|
算法 Java C语言
LeetCode 200:岛屿数量 Number of Islands
题目: 给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。 Given a 2d grid map of '1's (land) and '0's (water), count the number of islands.
803 0
|
Java 数据安全/隐私保护
[LintCode] Number of Islands(岛屿个数)
描述 给一个01矩阵,求不同的岛屿的个数。 0代表海,1代表岛,如果两个1相邻,那么这两个1属于同一个岛。我们只考虑上下左右为相邻。 样例 在矩阵: [ [1, 1, 0, 0, 0], [0, 1, 0, 0, 1], [0, 0, 0, 1, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 1] ] 中有 3 个岛。
1235 0