[LeetCode] Paint Fence
2015-09-05 12:24
351 查看
Problem Description:
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.
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
In each loop,
Finally, the return value
The code is as follows.
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.
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
dp1in the above post) and
d(different) with
d1and
d2to stand for the last two elements of
dp2in the above post.
In each loop,
dp1[i] = dp2[i - 1]turns into
s = d2and
dp2[i] = (k - 1) * (dp2[i - 2] + dp2[i - 1])becomes
d2 = (k - 1) * (d1 + d2). Moreover,
d1needs to be set to the old
d2, 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.
class Solution { public: int numWays(int n, int k) { if (n < 2 || !k) return n * k; int s = k, d1 = k, d2 = k * (k - 1); for (int i = 2; i < n; i++) { s = d2; d2 = (k - 1) * (d1 + d2); d1 = s; } return s + d2; } };
相关文章推荐
- java bufferedreader 与inputstream的区别
- CSS实现提示框的效果
- Html页中使用OCX控件
- WebBrowser中html元素如何触发winform事件
- jquery选择器(原创)<四>
- ExtJS Grid 每个Cell都显示tooltip
- JavaScript 函数创建思想
- scanner和BufferedReader
- HTML设置超链接字体颜色和点击后的字体颜色
- Sublime Text通过插件编译Sass为CSS及中文编译异常解决
- JS事件代理
- HDU3694 Fermat Point in Quadrangle(求四边形费马点)
- CSS基础知识
- 很火的ES5(js数组函数)初体验
- 学习笔记-AngularJs (一)
- js 获取页面内容可见区域的高度和宽度
- 揭秘AngularJS工作原理
- SharedPreferences总结
- PASSION之CSS3中2D,3D转化
- Ajax-JS