Skip to content

Latest commit

 

History

History
 
 

permutations

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

全排列

LeetCode地址

第一次

直接抄代码,老师讲的从上至下,递归的模板很管用

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        int len = nums.length;
        List<List<Integer>> res = new ArrayList<>();
        if (len == 0) return res;

        Deque<Integer> path = new ArrayDeque<>();
        boolean[] used = new boolean[len];
        _dfs(nums, len, 0, path, used, res);
        return res;
    }

    private void _dfs(int[] nums, int len, int depth, Deque<Integer> path
        , boolean[] used, List<List<Integer>> res) {
        if (depth == len) {
            res.add(new ArrayList<>(path));
            return;
        }

        for (int i = 0; i < len; i++) {
            if (used[i]) continue;
            path.addLast(nums[i]);
            used[i] = true;
            _dfs(nums, len, depth + 1, path, used, res);
            //回朔
            path.removeLast();
            used[i] = false;
        }
    }
}