計算n個組有n種排列方式的幾種算法

轉載自:https://blog.csdn.net/Mikchy/article/details/91383798

題目:
把一個數組裏的數的組合全部列出,比如1和2列來爲1,2,12,21.

分析:
這道題有多種擴展

1,沒有重複元素的數的組合

2,有重複元素的數的組合

3,沒有重複元素的數的全排列

4,有重複元素的數的全排列

1,沒有重複元素的數的組合
第一種情況下,沒有重複元素的數的組合,利用DFS直接求,因爲沒有重複元素,所以不會出現一樣的,將數組元素存在LinkedList裏(方便刪除),遍歷List,刪除當前元素並把此元素加入結果,如果結果長度不爲0,則輸出,以此遞歸。

public static void DFS(List<Integer> candidate, String prefix){
	if(prefix.length()!=0){
		System.out.println(prefix);
	}
	
	
	for(int i=0; i<candidate.size(); i++){
		
		List<Integer> temp = new LinkedList<Integer>(candidate);
		int item = (int)temp.remove(i);  // 取出被刪除的元素,這個元素當作一個組合用掉了
		DFS(temp, prefix+item);
	}
}
public static void main(String[] args) {
	
	Integer[] array = {1,2};
	List<Integer> list = Arrays.asList(array);
	DFS(list, "");
}

2,有重複元素的數的組合
第二種情況,存在重複元素,如果直接用第一種情況的代碼直接使用,可能會存在重複的,這裏的處理方法是把結果保存在一個HashSet裏,每得到一個結果,檢查HashSet裏是否已經存在,不存在才輸出。

public static void DFS(List<Integer> candidate, String prefix, HashSet<String> hs){
	if(prefix.length()!=0 && !hs.contains(prefix)){
		System.out.println(prefix);
		hs.add(prefix);
	}
	
	
	for(int i=0; i<candidate.size(); i++){
		
		List<Integer> temp = new LinkedList<Integer>(candidate);
		int item = (int)temp.remove(i);
		DFS(temp, prefix+item, hs);
	}
}
public static void main(String[] args) {
	
	Integer[] array = {1,1,2};
	List<Integer> list = Arrays.asList(array);
	HashSet<String> hs = new HashSet<String>();
	DFS(list, "", hs);
}

3,沒有重複元素的數的全排列
這種情況是全排列,所以只需要在第一種情況的輸出時,多加一個判斷條件,此時的輸入List 中無數據(說明已經全部使用來排列了)。

public static void DFS(List<Integer> candidate, String prefix){
	if(prefix.length()!=0 && candidate.size()==0){
		System.out.println(prefix);
	}
	
	
	for(int i=0; i<candidate.size(); i++){
		
		List<Integer> temp = new LinkedList<Integer>(candidate);
		int item = (int)temp.remove(i);  // 取出被刪除的元素,這個元素當作一個組合用掉了
		DFS(temp, prefix+item);
	}
}
public static void main(String[] args) {
	
	Integer[] array = {1,2};
	List<Integer> list = Arrays.asList(array);
	DFS(list, "");
}

4,有重複元素的數的全排列
這種情況是全排列,有重複元素,是第二種情況的擴展,所以只需要在第二種情況的輸出時,多加一個判斷條件,此時的輸入List 中無數據(說明已經全部使用來排列了)。

public static void DFS(List<Integer> candidate, String prefix, HashSet<String> hs){
	if(prefix.length()!=0 && !hs.contains(prefix) && candidate.size()==0){
		System.out.println(prefix);
		hs.add(prefix);
	}
	
	
	for(int i=0; i<candidate.size(); i++){
		
		List<Integer> temp = new LinkedList<Integer>(candidate);
		int item = (int)temp.remove(i);
		DFS(temp, prefix+item, hs);
	}
}
public static void main(String[] args) {
	
	Integer[] array = {1,1,2};
	List<Integer> list = Arrays.asList(array);
	HashSet<String> hs = new HashSet<String>();
	DFS(list, "", hs);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章