您的位置:首页 > 其它

整数划分(递归)

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)


参考博客
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: