zoukankan      html  css  js  c++  java
  • leetcode276- Paint Fence- easy

    There is a fence with n posts, each post can be painted with one of the k colors.

    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.

    Note:
    n and k are non-negative integers.

    DP。

    状态定义:same[i] 表示涂到第i根杆子的时候如果限制i和i-1颜色相同,总共有多少种刷的方法。 diffp[i] 表示涂到第i根杆子的时候如果限制i和i-1颜色不同,总共有多少种刷的方法。

    状态转移方程:same[i] = 1 * diff[i - 1];    diff[i] = (k - 1) * (diff[i - 1] + same[i - 1]);  都是当前自己可选的颜色种类 * i - 1与i - 2之间需不需要相同的取舍。

    返回结果:same[n - 1] + diff[n - 1]

    实现:

    class Solution {
        //same(n) = 1 * diff(n - 1)   diff(n) = (k - 1) * (diff(n - 1) + same(n - 1))
        public int numWays(int n, int k) {
            if (n <= 0 || k <= 0) {
                return 0;
            }
            
            int[] same = new int[n];
            int[] diff = new int[n];
            
            same[0] = 0;
            diff[0] = k;
            for (int i = 1; i < n; i++) {
                same[i] = 1 * diff[i - 1];
                diff[i] = (k - 1) * (diff[i - 1] + same[i - 1]);
            }
            return same[n - 1] + diff[n - 1];
            
        }
    }
  • 相关阅读:
    音乐
    脚本注释的作用
    JavaScript状态栏冒泡
    JavaScript动态显示时间
    正则表达式
    JavaScript数组的最大长度
    加密(编码)web.config中的信息(如:连接字符串)
    JavaScript实现EMAIL功能
    JavaScript检测分辨率
    JavaScript如何给网页滚动条加上颜色?
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7976650.html
Copyright © 2011-2022 走看看