整数划分(递归)
2017-05-27 10:04
169 查看
package test04; //元素n的划分,即存在某些数,n1,n2,n3,n4.....使得n1+n2+...=n //比如6的划分共有11种,Count(6,4)=9 /* 6 5+1 4+2 4+1+1 3+3 3+2+1 3+1+1+1 2+2+2 2+2+1+1 2+1+1+1+1 1+1+1+1+1+1 */ public class test01 { public static void main(String[] args) { int count = Count(6,4); System.out.println(count); } //Count(n,m)表示整数n的所有划分中,划分元素不大于m的划分的个数 public static int Count(int n,int m){ if(n<1||m<1){ return 0; } if(n==1){ return 1; } if(m==1){ return 1; } /* 当n<m时,由于划分中不可能出现负数,因此就相当于f(n,n); */ if(n<m){ return Count(n, n); } /* 当n=m时,根据划分中是否包含n,可以分为两种情况: (a)划分中包含m的情况,只有一个即{m}; (b)划分中不包含m的情况,这时划分中最大的数字也一定比m小,即n的所有(m-1)划分。 因此总的 f(n,m) =1 + f(n,m-1); */ if(n==m){ return Count(n, m-1)+1; } /* 当n>m时,根据划分中是否包含最大值m,可以分为两种情况: (a)划分中包含m的情况,即{m, {x1,x2,...xi}}, 其中{x1,x2,... xi} 的和为n-m,因此这情况下为f(n-m,m) (b)划分中不包含m的情况,则划分中所有值都比m小,即n的(m-1)划分,个数为f(n,m-1); 因此总的 f(n, m) = f(n-m, m)+f(n,m-1); */ else{ return Count(n, m-1)+Count(n-m, m); } } } 1; (n=1 or m=1) f(n,m) = f(n, n); (n<m) 1+ f(n, m-1); (n=m) f(n-m,m)+f(n,m-1); (n>m)
参考博客
相关文章推荐
- 算法篇-1-递归思想-整数划分&Fibonacci&Ackerman&Permutation&Hanoi
- 经典算法2:递归求解整数划分
- 递归 放苹果问题和整数划分问题
- 整数划分(递归)
- 2.1递归概念 - 对排序问题、整数划分问题、汉诺塔问题的理解
- nyoj 571 整数划分(三)(递归)
- YTU.3131: 进阶递归之简单的整数划分问题
- 整数划分的递归实现算法
- 递归 放苹果问题和整数划分问题
- nyoj 571 整数划分(三)(递归)
- 0002算法笔记——【递归】排列问题,整数划分问题,Hanoi问题
- 整数划分 ,DP 或者直接递归(备忘录消除重复)
- 整数划分 用递归,动态规划,母函数法实现
- [算法][递归] 整数划分 种类数
- 递归 放苹果问题和整数划分问题
- nyoj 90 整数划分(一) (dp||递归)
- nyoj 571 整数划分(三)(递归)
- 整数划分(递归)
- NYOJ90-整数划分,经典递归思想~~
- 递归-整数划分问题