LeetCode 46. Permutations (全排列)

题目标签:Backtracking

  利用dfs,建立一个 tempList, 递归加入每一个数字;

  因为数字都是不相同的,利用检查tempList 来跳过已用数字,具体看code。

 

Java Solution: 

Runtime:  1 ms, faster than 92.59 % 

Memory Usage: 41.5 MB, less than 5.68 %

完成日期:11/08/2019

关键点:数字没有重复

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

参考资料:LeetCode Discuss

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

posted @ 2020-03-09 04:23  Jimmy_Cheng  阅读(159)  评论(0编辑  收藏  举报