Special backtracking Leetcode of -46. Full array (Permutations)

Special backtracking Leetcode of -46. Full array (Permutations)

Given a sequence of numbers is not repeated, all possible return to full permutation.

Example:

Input: [1,2,3] 
Output: 
[ 
  [1,2,3], 
  [1,3,2], 
  [2,1,3], 
  [2,3,1], 
  [3,1,2 ], 
  [3,2,1] 
] 

analysis: using backtracking, backtracking vis array, indicating whether the selected number, e.g. vis [1] = 1 representing the selected number of the subscript 1.

AC Code:
class Solution {
List<List<Integer>> ans = new ArrayList<>();
    int vis[] = null;
    public List<List<Integer>> permute(int[] nums) {
        vis = new int[nums.length];
        Arrays.fill(vis,0);
        dfs(nums,0,new ArrayList<Integer>());
        
        return ans;
    }
    
    public void dfs(int nums[],int position,ArrayList<Integer> tmp){
        if(position>nums.length-1){
            if(tmp.size()==nums.length){
                ans.add(new ArrayList<>(tmp));
            }
            return;
        }
        
        
        for(int i=0;i<nums.length;i++){
            if(vis[i]==1) continue;
            
            vis[i] = 1;
            tmp.add(nums[i]);
            dfs(nums,position+1,tmp);
            tmp.remove(tmp.size()-1);
            vis[i] = 0;
        }
        
        
        
    }
}

 

Guess you like

Origin www.cnblogs.com/qinyuguan/p/11324789.html