Leetcode 276: Paint Fence

Posted Keep walking

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 276: 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.

 

 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 }

 


以上是关于Leetcode 276: Paint Fence的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 276. Paint Fence 粉刷篱笆

[LeetCode] 276. Paint Fence_Easy tag: Dynamic Programming

276. Paint Fence

276. Paint Fence

276. Paint Fence

LeetCode Paint Fence