Leetcode 276: Paint Fence

本文介绍了一种使用动态规划解决的计算机科学问题:如何给有n个柱子的围栏涂上k种颜色,使得任意相邻两个柱子的颜色不同或最多相同一次。文章提供了两种解决方案的Java代码实现。

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.

 

 1 public class Solution {
 2     public int NumWays(int n, int k) {
 3         if (n < 1 || k < 1) return 0;
 4         if (n == 1) return k;
 5         
 6         int dpSame = k, dpDifferent = k * (k - 1);
 7         
 8         for (int i = 2; i < n; i++)
 9         {
10             var tmp = dpSame;
11             dpSame = dpDifferent;
12             dpDifferent = (tmp + dpDifferent) * (k - 1); 
13         }
14         
15         return dpSame + dpDifferent;
16     }
17     
18     private int DFS(int n, int k, int start, int cur, bool sameColor)
19     {
20         if (start >= n)
21         {
22             return cur;
23         }
24         
25         if (sameColor)
26         {
27             return DFS(n, k, start + 1, cur * (k - 1), false);
28         }
29         else
30         {
31             return DFS(n, k, start + 1, cur, true) + DFS(n, k, start + 1, cur * (k - 1), false);
32         }
33     }
34 }
35 
36 // DFS, timeout
37 public class Solution1 {
38     public int NumWays(int n, int k) {
39         if (n < 1 || k < 1) return 0;
40         
41         return DFS(n, k, 1, k, false);
42     }
43     
44     private int DFS(int n, int k, int start, int cur, bool sameColor)
45     {
46         if (start >= n)
47         {
48             return cur;
49         }
50         
51         if (sameColor)
52         {
53             return DFS(n, k, start + 1, cur * (k - 1), false);
54         }
55         else
56         {
57             return DFS(n, k, start + 1, cur, true) + DFS(n, k, start + 1, cur * (k - 1), false);
58         }
59     }
60 }

 

转载于:https://www.cnblogs.com/liangmou/p/8054810.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值