首页 > 其他 > 详细

lintcode-easy-Paint Fence

时间:2016-04-07 08:16:50      阅读:276      评论:0      收藏:0      [点我收藏+]

There is a fence with n posts, each post can be painted with one of the kcolors.
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


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) {
        // Write your code here
        
        int[] diff = new int[n + 1];
        int[] same = new int[n + 1];
        
        diff[0] = 0;
        diff[1] = k;
        
        same[0] = 0;
        same[1] = 0;
        
        for(int i = 2; i <= n; i++){
            diff[i] = same[i - 1] * (k - 1) + diff[i - 1] * (k - 1);
            same[i] = diff[i - 1];
        }
        
        return diff[n] + same[n];
    }
}

 

lintcode-easy-Paint Fence

原文:http://www.cnblogs.com/goblinengineer/p/5362011.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!