Permutations

Constraint:


    1 <= nums.length <= 6
    -10 <= nums[i] <= 10
    All the integers of nums are unique.

Idea

Search:
if the size of permutation set is eaual to array size, add it to the final results list
For each number in the array in range [0, n):
if nums[i] is not visited, add it to the temp permuation set
repeat the search for other nums recursivly
remove nums[i] from the permutation set, and try the next possible index

Code

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> results = new ArrayList<>();
        boolean[] visited = new boolean[nums.length];
        search(nums, visited, new ArrayList<Integer>(), results);
        return results;
    }
    
    private void search(int[] nums, boolean[] visited, List<Integer> permutation, List<List<Integer>> results) {
        if (permutation.size() == nums.length) {
            results.add(new ArrayList<Integer>(permutation));
            return;
        }
        
        for (int i = 0; i < nums.length; i++) {
            if (!visited[i]) {
                permutation.add(nums[i]);
                visited[i] = true;
                search(nums, visited, permutation, results);
                visited[i] = false;
                permutation.remove(permutation.size() - 1);
            }
        }
    }
}
  • Time: O(n! * n) as we have to iterate all the possible permutation for an array. Making a copy of permutation list requires O(n) as well.
  • Space: O(n). We need an array to keep track of all the visited numbers. The recursion calls could go as deep as the size of array.

Similar problem:

  • Subsets
  • Subsets II
  • Permutations II

These all all backtracking problems and can be solved with similar code structures.

Permutations

上一篇:修改ubuntu20.04个人文件夹为英文


下一篇:性能测试工具jmeter的下载安装与脚本录制