[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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值