Skip to content

每个槽位可以选什么数字, dfs, 记录哪个数字用过了

java
class Solution {
    /**
     * 每个槽位可以选什么数字, dfs, 记录哪个数字用过了
     */
    public List<List<Integer>> permute(int[] nums) {
        int n = nums.length;
        List<List<Integer>> ans = new ArrayList<>();
        List<Integer> permutation = Arrays.asList(new Integer[n]);;
        dfs(0, nums, permutation, new boolean[n], ans);
        return ans;
    }

    private void dfs(int i, int[] nums, List<Integer> permutation, boolean[] visited, List<List<Integer>> ans) {
        if (i == nums.length) {
            ans.add(new ArrayList<>(permutation));
            return ;
        }
        for (int j = 0; j < nums.length; j++) {
            if (visited[j])
                continue;

            permutation.set(i, nums[j]);
            visited[j] = true;
            dfs(i+1, nums, permutation, visited, ans);
            visited[j] = false;
        }
    }
}

Personal Knowledge Base