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

Hide Company Tags Google
Hide Tags Dynamic Programming
Hide Similar Problems (E) House Robber (M) House Robber II (M) Paint House (H) Paint House II

机智的我看见这个题目就是排列组合问题啊,哈哈哈。但并没什么卵用,仔细一看,no more than two fences adjacently has same colors.

所以啊,最多可以有两个相邻的fence有同样的颜色。
假如我们有3种颜色,用3种颜色涂一个fence:3种方法。涂2个fence:每个fence有三种选择,所以有6种方法。但涂3个fence的时候就不是了。对于前两个fence每个都有3种选择,但对于最后一个fence, 有两种情况:
前两个要是是一样的颜色,它只能有两种选择。
前两个不一样,则有三种选择。
具体实例如下:
这里写图片描述

所以我们可以知道,对于当前C fence. 两种选择:
1. for previous two fences are same:

case1=(k1)same

2. for previous two fences are different:
case2=kdifferent

Then the total ways to paint three fences w/ three color are:
case1+case2

What if we add a new fence D?

For D:

newSame=oldDiff

newDiff=oldSame(k1)+oldDiff(k1)=(k1)(oldSame+oldDiff)

code:

class Solution {
public:
    int numWays(int n, int k) {
        if(!k ||!n ) return 0;
        if(n == 1) return k;
        int diff = k*(k-1); //last two posts are different;
        int same = k; // last two posts are same.
        for(int i = 2; i<n; ++i){
            int newSame = diff;
            int newDiff = (k-1) * (same + diff);
            diff = newDiff;
            same = newSame;
        }
        return same + diff;
    }
};

可以把code写简单一点。。比如:

class Solution {
public:
    int numWays(int n, int k) {
        if(!k ||!n ) return 0;
        if(n == 1) return k;
        int diff = k*(k-1); //last two posts are different;
        int same = k; // last two posts are same.
        for(int i = 2; i<n; ++i){
          int newSame = diff;
          diff = (k-1) * (diff + same);
          same = newSame;
        }
        return same + diff;
    }
};
发布了109 篇原创文章 · 获赞 0 · 访问量 4万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章