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

[LeetCode] Paint Fence

时间:2015-09-05 13:45:08      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:

A dynamic programming problem. This post shares a nice solution and explanation. Well, this article is simply an organization of this post and its first answer (also posted by me :-)).

I use s (same) to stand for the number of ways when the last two fences are painted with the same color (the last element of dp1 in the above post) and d (different) with d1 and d2 to stand for the last two elements of dp2 in the above post.

In each loop, dp1[i] = dp2[i - 1] turns into s = d2 and dp2[i] = (k - 1) * (dp2[i - 2] + dp2[i - 1]) becomes d2 = (k - 1) * (d1 + d2). Moreover, d1 needs to be set to the oldd2, which is recorded in s. So we have d1 = s.

Finally, the return value dp1[n - 1] + dp2[n - 1] is just s + d2.

The code is as follows.

 1 class Solution {
 2 public:
 3     int numWays(int n, int k) {
 4         if (n < 2 || !k) return n * k; 
 5         int s = k, d1 = k, d2 = k * (k - 1); 
 6         for (int i = 2; i < n; i++) {
 7             s = d2;
 8             d2 = (k - 1) * (d1 + d2);
 9             d1 = s;
10         }
11         return s + d2;
12     }
13 };

 

[LeetCode] Paint Fence

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4783051.html

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