• 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;
        }
    };
    
  • 相关阅读:
    Nginx介绍
    linux vi编辑
    MySql数据类型
    Mysql用户权限控制(5.7以上版本)
    Linux上安装MySQL
    Java得到指定日期的时间
    Spring Boot 整合Redis 实现缓存
    编写高效优雅Java程序
    JVM调优和深入了解性能优化
    JVM执行子程序
  • 原文地址:https://www.cnblogs.com/casperwin/p/13722235.html
Copyright © 2020-2023  润新知