Permutations

2021/8/6 6:07:55

本文主要是介绍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的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程