LeetCode Paint Fence

本文解析了LeetCode上的一道经典动态规划问题——涂栅栏问题。介绍了如何通过动态规划方法解决栅栏涂色问题,确保任意两个相邻栅栏柱颜色不同,并给出了Java实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接在这里:https://leetcode.com/problems/paint-fence/

题目:

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.

题解:

base case n == 1, 那么有k种图法. n==2时,若选择相同图法,有k种. 若不同图法,有k*(k-1)种方法,总共有sameColorLastTwo + diffColorLastTwo种方法。

DP时,当到了 i 时 有两种选择,第一种 i 和 i-1不同色,那么有 i-1的总共方法 * (k-1), 就是(sameColorLastTwo + diffColorLastTwo) * (k-1).

第二种用相同色,那么 i -1 和 i-2 必须用不同色, 就是i-1的diffColorLastTwo.

最后返回两种方法的和diffColorLastTwo + sameColorLastTwo.

注意check corner case, e.g. n == 0, return 0. k == 0, return 0.

Time Complexity: O(n). Space: O(1).                   

AC Java:

 1 public class Solution {
 2     public int numWays(int n, int k) {
 3         if(n<=0 || k<=0){
 4             return 0;
 5         }
 6         if(n == 1){
 7             return k;
 8         }
 9         int sameColorLastTwo = k;
10         int diffColorLastTwo = k*(k-1);
11         for(int i = 3; i<=n; i++){
12             int temp = diffColorLastTwo;
13             diffColorLastTwo = (sameColorLastTwo + diffColorLastTwo) * (k-1);
14             sameColorLastTwo = temp;
15         }
16         return diffColorLastTwo + sameColorLastTwo;
17     }
18 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/5244046.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值