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;
    }
}

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