[leetcode] 276. Paint Fence 解题报告

来源:互联网 发布:vm安装linux虚拟机 编辑:程序博客网 时间:2024/06/05 07:32

题目链接:https://leetcode.com/problems/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.


思路: 题意说的是不能有超过连续两个相同的颜色, 也就是说最多有两个相邻柱子染同样颜色.

所以在染一个柱子的时候, 要考虑是否和上一个柱子颜色相同. 

如果和上一个相同的话那么上一个有多少种和上上次不同的染色方案, 那么当前柱子也有多少种染色方案.

如果和上一个不同的话那么染色方案就为(k-1)*(之前总共多少染色方案).

代码如下:

class Solution {public:    int numWays(int n, int k) {        if(n==0 || k==0 || (k==1 && n>2)) return 0;        int same = 0, diff = k, total = k;        for(int i = 2; i <= n; i++)        {            same = diff, diff = (k-1)*total;            total = same + diff;        }        return total;    }};
参考: https://leetcode.com/discuss/85147/complete-explanation-o-n-time-o-1-space

0 0
原创粉丝点击