m個數隨機取n個數的java實現

//借用他人的C語言版本改成java版本 同時懶懶地增加了順序輸出結果
 
 static int total = 0;
 
 static void cur(int k, int m, int n, List usedList, List resultList, List arrayList)
 {
     if (k<n)
     {
         for (int x=0;x<m;x++)
         {
             if ((Integer)usedList.get(x)==0)//not used
             {
              usedList.set(x, 1);
              resultList.set(k,arrayList.get(x));
                 //遞歸
                 cur(k+1,m,n, usedList, resultList, arrayList);
                 //遞歸未調用遞歸時(即k>=0||x!=0)執行這一句
                 usedList.set(x, 0);
             }
         }
     }
     else
     {
//      隨機排列結果全集輸出
//      ++total;
//         for (int i=0;i<n;i++){
//          System.out.print(resultList.get(i));
//         }
//         System.out.println();
      
//      判斷從小到大排列的,輸出
      int temp = -2;
         for(int j=0;j<n;j++){
          if(temp<(Integer)resultList.get(j)){
           temp = (Integer)resultList.get(j);
           if(j==n-1){
            ++total;
            temp = -2;
               for (int i=0;i<n;i++){
             System.out.print(resultList.get(i));
            }
               System.out.println();
           }
          }else{
           //此結果不予輸出
           break;
          }
         }
     }
 }

 

 public static void main(String[] args) { 
  int m=10;
  int n=6;
  //10個數字內取6個亂序:6*5*4*3*2*1*((10*9*8*7)/(4*3*2*1))
  List arrayList  = new ArrayList();
  List usedList  = new ArrayList();
  List resultList  = new ArrayList();
  for(int i=0;i<m;i++){
   arrayList.add(i);
  }
  for(int i=0;i<m;i++){
   usedList.add(0);
  }
  for(int i=0;i<n;i++){
   resultList.add(-1);
  }
     cur(0,m,n,usedList,resultList,arrayList);
    
     System.out.println("total:"+total);
 }