- import java.util.Scanner;
- public class bp
- {
- static int n;
- static int count=0;//count为统计集合元素的个数
- static int []d=new int[25];//存放集合中的每个元素
- static void divide(int number,int idx)
- {
- if(number==0)
- {
- if(count==0)
- {
- System.out.print(n+"->");
- System.out.print("{");
- }
- for(int i=0;i<idx;i++)
- {
- if(i==0&&(n/2>1))
- System.out.print("[");
- if(i>0)
- System.out.print(",");
- System.out.print(d[i]);
- }
- if(n/2>1) System.out.print("]");
- if(idx<n/2)
- System.out.print(",");
- else
- System.out.println("}");
- count++;//元素个数自增
- return;
- }
- for(int i=number;i>=2;i--)//从大到小开始选数
- {
- if(idx==0||i<=d[idx-1])//用来保证右边的数不大于左边的
- {
- d[idx]=i;
- divide(number-i,idx+1);//递归
- }
- }
- }
- public static void main(String[] args)
- {
- Scanner sc=new Scanner(System.in);
- while(sc.hasNextInt())
- {
- count=0;
- n=sc.nextInt();
- divide(n,0);//递归
- }
- }
- }
复制代码 运行结果如下:2
2->{2}
3
3->{3}
4
4->{[4],[2,2]}
5
5->{[5],[3,2]}
6
6->{[6],[4,2],[3,3],[2,2,2]}
7
7->{[7],[5,2],[4,3],[3,2,2]}
8
8->{[8],[6,2],[5,3],[4,4],[4,2,2],[3,3,2],[2,2,2,2]}
不会上传截图 |