LeetCode 46. Permutations (full array)

Topic Tags: Backtracking

  Using dfs, establishing a tempList, recursive added to each number;

  Because the numbers are not the same, to the use of skips checking digital tempList specific look code.

 

Java Solution: 

Runtime:  1 ms, faster than 92.59 % 

Memory Usage: 41.5 MB, less than 5.68 %

Completion Date: 11/08/2019

The key point: there are no duplicate numbers

class Solution {
    
    List<List<Integer>> res;
    
    public List<List<Integer>> permute(int[] nums) {
        res = new ArrayList<>();
        List<Integer> tempList = new ArrayList<>();
        //Array.sort(nums);
        DFS(nums, tempList);
        
        return res;
    }
    
    private void DFS(int[] nums, List<Integer> tempList) {
        if(tempList.size() == nums.length) {
            res.add(new ArrayList<>(tempList));
            return;
        }
        
        for(int i=0 ; i<nums.length; i++) {
            if(tempList.contains(nums[i])) // if this number already exists, skip it.
                continue;
            
            tempList.add(nums[i]);
            DFS(nums, tempList);
            tempList.remove(tempList.size() - 1);
        }
    }
}

Reference: LeetCode Discuss

LeetCode title list -  LeetCode Questions List

Topic Source: https: //leetcode.com/

Guess you like

Origin www.cnblogs.com/jimmycheng/p/12446558.html