分治法實現1-N的數字按字典序全排列組合 Java語言


package 分治法;


import java.util.Arrays;
/*
 * 將數字 1 - n進行全排列  按字典序從小到大輸出
 * 如  1 - 3  
 * 	123 132 213 231 312 321
 */
class GenerateP{
	
	private int n;  //  求 1-n所有數字的全排列
	private final int maxn = 110;//最多可排列組合的長度  1-100
	private boolean [] hashTable;
	private int [] p;
	
	public GenerateP(int n) {
		// TODO Auto-generated constructor stub
		this.n = n;
		hashTable = new boolean[maxn];
		p = new int [maxn];
		Arrays.fill(hashTable, false);
		Arrays.fill(p, 0);
	}
	public void generatep(int index){
		if(index == n + 1){
			for(int i = 1; i <= n; i++){
				System.out.print(p[i]);
			}
			System.out.println();
			return;
		}
		
		for(int x = 1; x <= n; x++){
			if(hashTable[x] == false){
				p[index] = x;
 				hashTable[x] = true;
				generatep(index + 1);
				hashTable[x] = false;
			}
		}
	}
}
public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		GenerateP generateP = new GenerateP(3);
		generateP.generatep(1);

	}

}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM