46. 全排列

46. 全排列

回溯

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    boolean[] vis;

    public List<List<Integer>> permute(int[] nums) {
        vis = new boolean[nums.length];
        backtrack(nums);
        return res;
    }

    void backtrack(int[] nums){
        if(path.size() == nums.length){
            res.add(new ArrayList<>(path));
            return;
        }

        for(int i = 0; i < nums.length; i++){
            if(vis[i]) continue;
            path.add(nums[i]);
            vis[i] = true;
            backtrack(nums);
            vis[i] = false;
            path.remove(path.size() - 1);
        }
    }
}

你可能感兴趣的:(#,HOT100,算法)