LeetCode 276. Paint Fence
2016-05-05 11:49
232 查看
#include <iostream> #include <vector> using namespace std; /* 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 colors. Return the total number of ways you can paint the fence. Note: n and k are non-negative integers. */ /* It is better to use an example to illustrate the question. if n == 0, return 0 method. if n == 1, return k method (1 post can have k colors) // k-1 is the colors for second post different from the first one. // 1 is the color that same as first post. if n == 2, return k * (k - 1) + k * 1. // (k * 1 * (k-1) + k * (k - 1) * (k - 1)) is the choice that different from second post. // (k * (k-1) + k * 1) * 1, is the choice that same color as second post. if n == 3, return (k * 1 * (k-1) + k * (k - 1) * (k - 1)) + (k * (k-1) + k * 1) * 1 */ int numOfWays(int n, int k) { if(n == 0) return 0; if(n == 1) return k; int same_color = k; int different_color = k * (k - 1); for(int i = 3; i <= n; ++i) { int tmp = different_color; different_color = different_color * (k-1) + same_color * (k-1); same_color = tmp * 1; } return different_color + same_color; } int main(void) { cout << numOfWays(3, 2) << endl; }
相关文章推荐
- javascript 经典案例
- Javascript函数[实用案例--网页抽奖]
- CSS截图图片的几种方式
- WPF显示html的几种方法
- Js打开新窗口拦截问题整理
- 代替jquery $.post 跨域提交数据的N种形式
- CSS3动画在安卓手机上无效
- nodejs的process模块如何获取其他进程的pid
- asp.net+jquery.form实现图片异步上传的方法(附jquery.form.js下载)
- prufer序列
- javascript练习题(六)
- Extjs插入图片
- jQuery 向 servlet 发送和接受JSON数据。
- Map (就一个json.jar)
- JavaScript 关键字
- JavaScript 关键字
- css文本换行相关属性及解释
- repo+git 仓库搭建
- Bootstrap嵌入jqGrid,使你的table牛逼起来
- Struts2+jquery.form.js实现图片与文件上传的方法