用java實現對數組的排列組合

來源:互聯網
上載者:User

本程式旨在將數組所有排列結果顯示出來,所作的演算法。

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;

public class Range {
 private static int count = 0;

//迴圈的次數
 private static int loopTime = 0;

//儲存結果的容器
 private static ArrayList ls = new ArrayList();
 
 public static void main(String[] args) {

  long l1 = Calendar.getInstance().getTimeInMillis();
  Integer[] result = new Integer[6];

  //輸入的數組為 1, 2, 3, 4, 5 也可以為任意多數組
  ArrayList al = new ArrayList(6);
  al.add(new Integer(1));
  al.add(new Integer(2));
  al.add(new Integer(2));
  al.add(new Integer(3));  
  al.add(new Integer(4));
  al.add(new Integer(5));

  //遞規調用

  rotate(result, al, al.size());  

  
  for(int i=0 ; i< ls.size(); i++){
   System.out.print("this is the " + ++count + " number: ");
   System.out.println(ls.get(i));
  }
  long l2 = Calendar.getInstance().getTimeInMillis();
  System.out.println("consume time seconds is: " + (l2-l1));
  System.out.println("loopTime is: " + loopTime);
 }

//遞規方法
 public static void rotate(Integer[] result, List al, int index){
  index = result.length - index;
  if(index == result.length-1){   
    ++loopTime;
    result[index] = (Integer)al.get(0);        
    organizeNum(result);   
  }
  for (int s1 = 0; s1 < al.size(); s1++) {
   result[index] = (Integer)al.get(s1);   
   ArrayList al1 = new ArrayList(al);
   al1.remove(result[index]);
   rotate(result, al1, al1.size());
  }
 }

//加入容器
 public static void organizeNum(Integer[] result){
  StringBuffer sb = new StringBuffer();
  for(int i=0; i<result.length; i++){
   sb.append(result[i].toString());
  }
   String pstr = sb.toString();

    ls.add(pstr);
  
 } 

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.