TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
输出整数划分的所有结果。将正整数N划分为r个正整数之和(r=1,2,3,...N),输出所有划分结果。
程序:
- import java.util.*;
- public class Test{
-
- static int result[]=new int[100];
- static int r=0;
- static int N=0;
- public static void main(String aargs[]){
-
- System.out.printf("please input a number(0< N< 100):");
- Scanner sc=new Scanner(System.in);
- while(sc.hasNext()){
- N=sc.nextInt();
- if(N==0) break;
- for( r=N;r>0;r--)
- zuhe(N,r);
- }
- }
- public static void zuhe(int m,int k)
- {
-
- int i,j;
- for(i=m;i>=1;i--)
- {
- result[k-1]=i;//第k-1个位置可以排 m,m-1,...1
- if(k>1)
- zuhe(i,k-1);//递归排第k-2个位置,...
- else
- {
-
- int temp=0;
- for(j=0;j< r;j++)
- temp+=result[j];//k个位置之和
- if(temp==N)//当前组合是整数N的一个拆分
- {
- for(j=0;j< r;j++)
- System.out.printf("%4d",result[j]);
- System.out.printf("
- ");
- }
- }
- }
- }
- }
- C: >javac Test.java
- C: >java Test
- please input a number(0< N< 100):9
- 1 1 1 1 1 1 1 1 1
- 1 1 1 1 1 1 1 2
- 1 1 1 1 1 1 3
- 1 1 1 1 1 2 2
- 1 1 1 1 1 4
- 1 1 1 1 2 3
- 1 1 1 2 2 2
- 1 1 1 1 5
- 1 1 1 2 4
- 1 1 1 3 3
- 1 1 2 2 3
- 1 2 2 2 2
- 1 1 1 6
- 1 1 2 5
- 1 1 3 4
- 1 2 2 4
- 1 2 3 3
- 2 2 2 3
- 1 1 7
- 1 2 6
- 1 3 5
- 2 2 5
- 1 4 4
- 2 3 4
- 3 3 3
- 1 8
- 2 7
- 3 6
- 4 5
- 9
- 0
- C: >
复制代码
源码下载:http://file.javaxxz.com/2014/12/2/000636359.rar |
|