• 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;
        }
    };
    
  • 相关阅读:
    商品翻牌效果(纯css)
    3D旋转相册(纯css)
    3D旋转
    前端搜索js
    js打字的效果
    淡入淡出,类似于轮播图
    返回顶部
    java设计模式--状态模式
    java设计模式--抽象工厂模式
    java设计模式--观察者模式
  • 原文地址:https://www.cnblogs.com/casperwin/p/13722235.html
Copyright © 2020-2023  润新知