排列组合算法

采用递归、回溯方法:

  // 排列组合
  private   static   void  combine( int  n) {
  
boolean[] selected=new boolean[n];
  Arrays.fill(selected, 
false);
  
int[] v=new int[n];
  Arrays.fill(v, 
-1);
  doCombine(selected,v,n,
0);
 }

 
 
// selected 已选择标识
 
// filledCount 已填充个数
  private   static   void  doCombine( boolean [] selected,  int [] v,  int  n,  int  filledCount) {
  
for(int i=filledCount;i<n;i++){
   
for(int j=0;j<n;j++){
    
if(!selected[j]){
     selected[j]
=true;
     v[i]
=j+1;
     
     
if(i==n-1){
      dumpIfFullFilled(v);
     }

     
     doCombine(selected,v,n,i
+1); 

     
//回溯
     selected[j]=false;
     v[i]
=-1;
    }

   }
   
      
  }

 }

 
 
private   static   void  dumpIfFullFilled( int [] v) {
  String s
="";
  
for(int i=0;i<v.length;i++){
   
if(v[i]==-1){
    
return;
   }

   s
+=v[i]+" ";
  }

  System.out.println(s);
 }
 

 

测试

  combine(4);

输出

1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 1 3
2 4 3 1
3 1 2 4
3 1 4 2
3 2 1 4
3 2 4 1
3 4 1 2
3 4 2 1
4 1 2 3
4 1 3 2
4 2 1 3
4 2 3 1
4 3 1 2
4 3 2 1

你可能感兴趣的:(排列组合算法)