栅栏染色
来源:互联网 发布:sqlserver数据库维护 编辑:程序博客网 时间:2024/04/20 03:52
我们有一个栅栏,它有
public class Solution {
/**
* @param n non-negative integer, n posts
* @param k non-negative integer, k colors
* @return an integer, the total number of ways
*/
public int numWays(int n, int k) {
// Write your code here
//题目应改为至多有两根相邻柱子颜色相同
if(k<1||n<1)
return 0;
if(n==1)//只有一根柱子时
return k;
if(n==2)
return k*k;//可以相同
int[] res= new int[n];
res[0]=k;
res[1]=k*k;
for(int i=2;i<n;i++)
res[i]=res[i-1]*(k-1)+res[i-2]*(k-1);
//当最后一根柱子跟前一根颜色相同时,有res[i-2]*(k-1)种方案
//当最后一根与前一根不同时,有res[i-1]*(k-1)种方案
return res[n-1];
}
}
n
个柱子,现在要给柱子染色,有k
种颜色可以染。必须保证任意两个相邻的柱子颜色不同【应改为最多有两个相邻柱子颜色相同】,求有多少种染色方案。
样例
n
= 3, k
= 2, return 6
post 1, post 2, post 3way1 0 0 1 way2 0 1 0way3 0 1 1way4 1 0 0way5 1 0 1way6 1 1 0
/**
* @param n non-negative integer, n posts
* @param k non-negative integer, k colors
* @return an integer, the total number of ways
*/
public int numWays(int n, int k) {
// Write your code here
//题目应改为至多有两根相邻柱子颜色相同
if(k<1||n<1)
return 0;
if(n==1)//只有一根柱子时
return k;
if(n==2)
return k*k;//可以相同
int[] res= new int[n];
res[0]=k;
res[1]=k*k;
for(int i=2;i<n;i++)
res[i]=res[i-1]*(k-1)+res[i-2]*(k-1);
//当最后一根柱子跟前一根颜色相同时,有res[i-2]*(k-1)种方案
//当最后一根与前一根不同时,有res[i-1]*(k-1)种方案
return res[n-1];
}
}
0 0
- 栅栏染色
- 栅栏染色
- 栅栏染色
- 栅栏染色
- 栅栏染色
- 栅栏染色
- LintCode:栅栏染色
- lintcode栅栏染色
- 栅栏染色-动态规划
- LintCode之栅栏染色
- Lint-Code栅栏染色
- LintCode 栅栏染色
- LintCode: 栅栏染色
- 栅栏染色-LintCode
- 栅栏染色-LintCode
- lintcode 栅栏染色
- LintCode 栅栏染色
- lintcode paint-fence 栅栏染色
- 【JS】时间走动特效用封装函数在小于10的数的前面加0
- NanoHTTPD----SimpleWebServer初始化
- Android烧录程序后第一次开机时间优化
- Java的接口和抽象类
- ajax与XML
- 栅栏染色
- msyql get_lock()与RELEASE_LOCK()
- TortoiseSVN新人使用指南
- Android事件机制之一:事件传递和消费
- springMVC(6)------POJO绑定请求参数
- 【fiddler】抓取的https的会话记录时出现有“Tunnel to ...443”的会话记录
- 再议大数据的本质特征
- js读取本地图片进行预览,上传服务器
- JAVA开发10--加载相对路径下配置文件并读取内容