首页 > 其他 > 详细

Permutations

时间:2021-08-06 10:26:00      阅读:22      评论:0      收藏:0      [点我收藏+]

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

原文:https://www.cnblogs.com/blackraven25/p/15106701.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!