zoukankan      html  css  js  c++  java
  • [LC] 47. Permutations II

    Given a collection of numbers that might contain duplicates, return all possible unique permutations.

    Example:

    Input: [1,1,2]
    Output:
    [
      [1,1,2],
      [1,2,1],
      [2,1,1]
    ]

    Time: O(N!)
    Space: O(N)

    class Solution:
        def permuteUnique(self, nums: List[int]) -> List[List[int]]:
            res = []
            if nums is None or len(nums) == 0:
                return res
            self.dfs(nums, 0, res)
            return res
        
        def dfs(self, nums, level, res):
            if level == len(nums):
                res.append(list(nums))
                return
            my_set = set()
            for i in range(level, len(nums)):
                if nums[i] not in my_set:
                    my_set.add(nums[i])
                    nums[i], nums[level] = nums[level], nums[i]
                    self.dfs(nums, level + 1, res)
                    nums[i], nums[level] = nums[level], nums[i]
    class Solution {
        public List<List<Integer>> permuteUnique(int[] nums) {
            List<List<Integer>> arrList = new ArrayList<>();
            List<Integer> list = new ArrayList<>();
            boolean[] visited = new boolean[nums.length];
            Arrays.sort(nums);
            helper(arrList, list, visited, nums);
            return arrList;
        }
        
        private void helper(List<List<Integer>> arrList, List<Integer> list, boolean[] visited, int[] nums) {
            if (list.size() == nums.length) {
                arrList.add(new ArrayList<>(list));
                return;
            }   
            for (int i = 0; i < nums.length; i++) {
                if (visited[i] || (i > 0 && nums[i] == nums[i - 1] && !visited[i - 1])) {
                    continue;
                }
                visited[i] = true;
                list.add(nums[i]);
                helper(arrList, list, visited, nums);
                list.remove(list.size() - 1);
                visited[i] = false;
            }
        }
    }
  • 相关阅读:
    Stack的一种简单实现
    Allocator中uninitialized_fill等函数的简单实现
    Allocator的简易实现
    编写自己的迭代器
    简单的内存分配器
    vector的简单实现
    异常类Exception
    intent大致使用
    java初识集合(list,set,map)
    php分页
  • 原文地址:https://www.cnblogs.com/xuanlu/p/11664671.html
Copyright © 2011-2022 走看看