[LeetCode] Paint Fence
2015-09-06 11:01
120 查看
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.
动态规划,可以使用滚动数组节省空间。dp[i][j][0]表示第i个fence的颜色为j,同时与第i-1个fence颜色不同的方案数;dp[i][j][1]表示第i个fence的颜色为j,同时与第i-1个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.
动态规划,可以使用滚动数组节省空间。dp[i][j][0]表示第i个fence的颜色为j,同时与第i-1个fence颜色不同的方案数;dp[i][j][1]表示第i个fence的颜色为j,同时与第i-1个fence颜色相同的方案数。
class Solution { public: int numWays(int n, int k) { if (n == 0 || k == 0) return 0; if (n == 1) return k; int dp[2][k][2]; for (int j = 0; j < k; ++j) { dp[0][j][0] = 1; dp[0][j][1] = 0; } for (int i = 1; i < n; ++i) { int sum = 0; for (int j = 0; j < k; ++j) { sum += (dp[(i-1)%2][j][0] + dp[(i-1)%2][j][1]); } for (int j = 0; j < k; ++j) { dp[i%2][j][1] = dp[(i-1)%2][j][0]; dp[i%2][j][0] = sum - dp[(i-1)%2][j][0] - dp[(i-1)%2][j][1]; } } int res = 0; for (int i = 0; i < k; ++i) { res += dp[(n-1)%2][i][0] + dp[(n-1)%2][i][1]; } return res; } };
相关文章推荐
- jQuery 中 attr 和 prop 的区别分析
- JSP或HTML的命名规范
- JS对象深度克隆
- jQuery.extend 函数详解
- org.w3c.dom.Node 转换成xml string
- jquery实现初次打开有动画效果的网页TAB切换代码
- Java中三个引用类SoftReference 、 WeakReference 和 PhantomReference的区别
- json教程系列(5)-json错误解析
- Javascript模块化编程-初识[1]
- json教程系列(4)-optXXX方法的使用
- 了解 JavaScript (4)– 第一个 Web 应用程序
- Gson:比较两个JSON字符串是否完全相等
- domino定时重启
- 在html静态页面按钮链接,给button加上提交的链接等方法
- json教程系列(1)-使用json所要用到的jar包下载
- js 作用域链&内存回收&变量&闭包
- js实现简洁的TAB滑动门效果代码
- 写个html下载swf
- 留言板——准备工作
- IE浏览器请求json数据弹出下载框问题