lintcode-easy-Paint Fence

本文讨论了如何使用编程解决一个特定的数学问题:给定n个柱子和k种颜色,找出所有可能的涂漆方式,使得不超过两个相邻的柱子颜色相同。通过迭代算法计算总的可能性数量。

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];
    }
}

 

转载于:https://www.cnblogs.com/goblinengineer/p/5362011.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值