Leetcode 全排列 和 回溯算法的笔记

Leetcode46 全排列 回溯算法

link

输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]

此题使用的 树形回溯算法 Backtracking 就是在 深度优先DFS 的基础上加上 状态恢复 ,来保证在当前层的状态不变,进而保证在本层Loop时对其他路径没有影响。

Leetcode 全排列 和 回溯算法的笔记_第1张图片
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {
    private List<List<Integer>> res; 
    public List<List<Integer>> permute(int[] nums) {
        int len = nums.length;
        res = new ArrayList<>();
        if (len == 0){
            return res;
        }
        Set<Integer> visited = new HashSet<>();
        
        List<Integer> path = new ArrayList<>();
        dfs(nums, path, visited, 0);
        return res;
    }

    private void dfs(int[] nums, List<Integer> path, Set<Integer> visited, int depth){
        if(depth == nums.length){
            res.add(new ArrayList<>(path));
            return;
        }

        for (int i = 0; i < nums.length; i++){
            if (!visited.contains(i)){
                path.add(nums[i]);
                visited.add(i);
                dfs(nums, path, visited, depth+1);
                visited.remove(i);
                path.remove(path.size()-1);
            }
        }
    }
}

你可能感兴趣的:(Leetcode 全排列 和 回溯算法的笔记)