• 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];
            
        }
    }
  • 相关阅读:
    一周内签到连续天数求解
    int型动态数组总结
    快速排序总结
    希尔排序总结
    冒泡排序的总结
    桶排序总结
    插入排序的总结
    选择排序的总结
    二分法的五种实现
    安装Yum源
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7976650.html
Copyright © 2020-2023  润新知