码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 276: Paint Fence

时间:2017-12-18 11:58:44      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:each   als   start   more   can   time   turn   esc   integer   

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

标签:each   als   start   more   can   time   turn   esc   integer   

原文地址:http://www.cnblogs.com/liangmou/p/8054810.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!