30 Day Challenge Day 12 | Leetcode 276. Paint Fence

题解

动态规划。

Easy

class Solution {
public:
    int numWays(int n, int k) {
        if(n == 0) return 0;
        if(n == 1) return k;

        int num = 0;
        
        // dp1[i]: the number of ways till the i-th post which always diffs with prevous one
        // dp2[i]: the number of ways till the i-th post which always is same with prevous one
        vector<int> dp1(n), dp2(n);
        
        dp1[0] = k;
        dp2[0] = 0;
        
        // i-1, i-2 has the same color: dp[i-2] * (k-1)
        // i-1, i-2 has different colors: dp[i-2] * (k-1) * k
        for(int i = 1; i < n; i++) {
            dp1[i] = dp1[i-1] * (k-1) + dp2[i-1] * (k-1);
            dp2[i] = dp1[i-1];
        }
        
        return dp1[n-1] + dp2[n-1];
    }
};

通常因为结果只需要数组中最后一个值,所以可以进行空间优化,用两个变量代替数组。

class Solution {
public:
    int numWays(int n, int k) {
        if(n == 0) return 0;

        int diff = k, same = 0, res = diff + same;

        for(int i = 1; i < n; i++) {
            same = diff;
            diff = res * (k-1);
            res = diff + same;
        }
        
        return res;
    }
};
原文地址:https://www.cnblogs.com/casperwin/p/13722235.html