514. Paint Fence

Posted lawrenceseattle

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了514. 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.

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
Notice
n and k are non-negative integers.
public class Solution {
    /**
     * @param n: non-negative integer, n posts
     * @param k: non-negative integer, k colors
     * @return: an integer, the total number of ways
     */
    public int numWays(int n, int k) {
        if(k == 0 || n == 0) return 0;
        //对于第一个来说,相当于跟之前的不一样,所以diff是k
        int diff = k;
        int same = 0;
        for(int i = 2; i <= n; i++) {
            int temp = diff;
            // 如果当前的和上一个不同,那么就是在上一个的基础上*(k-1)
            diff = (same + diff) * (k-1);
            //如果当前的和上一个相同,那么上一个和上上一个肯定不相同
            //所以方法数就是上一个diff的值
            same = temp;
        }
        return same + diff;
    }
}

以上是关于514. Paint Fence的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode Paint Fence

Leetcode 276: Paint Fence

Paint Fence

276. Paint Fence

Paint Fence

276. Paint Fence