leecode---46---array, dfs---find all combinations of arrays

Create a boolean array to record the usage of each number in the array.
Input parameters of dfs: final result, current result, original array, array boolean value.
Record the result if the current result length is equal to the array length.
Otherwise, traverse the boolean value of the array from the first position. If it is false, it means that it has not been used, then save this parameter into the current array and change the boolean value to false, and then perform the next dfs.
Finally, the parameter at this position needs to be popped, because this parameter can be replaced by other parameters.
 
 

 
 
meaning of the title
[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]
]
 
 
analyze
1. To determine whether a number has been used before, you must
 
 
code
class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> item = new ArrayList<Integer>();
        
        if(nums.length==0||nums==null)
            return res;
        boolean[] visited = new boolean[nums.length];  
        
        dfs(res,item,nums,visited);
        return res;
    }
    
    public void dfs(List<List<Integer>> res,List<Integer> temp,int[] nums,boolean[] visited) {
        //dfs termination condition
        if (temp.size() == nums.length) {
            res.add(new ArrayList(temp));
        }
        //First of all, the traversal of this dfs does not start from a certain pos position, but from the beginning, because the previous parameters may not be used
        //Otherwise continue to the next layer, which is to add a number to temp
        //It is also to traverse which number is used or not, and add it if it is not used
        for (int i=0;i<nums.length;i++){
            if(visited[i] == false){
                temp.add(nums[i]);
                visited[i] = true;
                dfs(res,temp,nums,visited);
                temp.remove(temp.size() - 1);
                visited[i] = false;
            }
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325249483&siteId=291194637