46. Permutations

打印一個數組的全排列算法

題目:

Given a collection of distinct numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:

[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

思路:用dfs深度優先搜索做

代碼:

class Solution {
    int []visit;//標記是否搜索過的數組
    List<List<Integer>> result;//要放回的結果list
    int len;
    int [] Allnums;//引用輸入數組
    int [] result_arr;//保存每一種排列情況的數組
    void dfs(int depth){
    	if(depth==len){
    		List <Integer> item=new ArrayList<>();//把其中的一種排列情況轉化爲list存起來
    		int arrLen=result_arr.length;
    		for(int j=0;j<arrLen;j++){
    			item.add(result_arr[j]);
    		}
    		result.add(item);
    	}
    	else{
    		for(int i=0;i<len;i++){
    			if(visit[i]==0){
    				result_arr[depth]=Allnums[i];//vist[i]==0表示沒訪問過,則搜索該元素
    				visit[i]=1;//標記已經搜索過該元素
    				dfs(depth+1);//繼續深搜
    				visit[i]=0;//回溯,讓該元素回到未被搜索過狀態
    			}
    		}
    	}
    }
    public List<List<Integer>> permute(int[] nums) {
        Allnums=nums;
    	result=new ArrayList<>();
        len=nums.length;
        result_arr=new int[len];
        visit=new int[len];
        dfs(0);
        return result;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章