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];
            
        }
    }
  • 相关阅读:
    python基本数据类型之字符串(二)
    python基本数据类型之字符串(一)
    Java基础之Java简介
    1024lab-How to run project using .ipynb
    pytorch调试工具
    关于深度学习选择和使用GPU
    中文文本预处理
    GCN相关
    Bert project Debug记录
    图卷积相关的参考
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7976650.html
Copyright © 2011-2022 走看看