[Locked] Paint Fence
2016-02-27 11:30
253 查看
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.
分析:
这题看起来能直接用公式输出答案吧...如果觉得公式算起来麻烦,那么对于连续排列串,而且只需要得到可以涂的种类数,故应可用动态规划解决。
代码:
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.
分析:
这题看起来能直接用公式输出答案吧...如果觉得公式算起来麻烦,那么对于连续排列串,而且只需要得到可以涂的种类数,故应可用动态规划解决。
代码:
int totalways(int n, int k) { if(n == 0 || n == 1 || k == 0) return k; int ls = k, ld = k * (k - 1); for(int i = 2; i < n; i++) { int temp = ls; ls = ld; ld = (temp + ld) * (k - 1); } return ls + ld; }
相关文章推荐
- Angular2教程(一)
- 了解JavaScript 对象属性的标签
- Plus One--JavaScript
- javascript先序遍历DOM树的方法
- js中匿名函数的递归
- js闭包
- JSP基本语法、3个编译指令、7个动作指令、9个内置对象
- Angularjs中设置cookies的过期时间
- 简单的圆形图标鼠标hover效果 | CSS3教程
- JSON-JQuery常用技巧
- 在Angular外部使用js调用Angular控制器中提供的函数方法或变量
- MVC4 @RenderBody、@RenderSection、@RenderPage、Html.RenderPartial、Html.RenderAction的作用和区别
- JS重点特性——闭包详解
- 关于CSS的简单描述
- <javascript>每日一记
- html-label标签
- javascript介绍
- 前端样式学习
- jquery总结
- JavaScript开发者必备的10个Sublime Text插件