Permutations II 解答

Posted ireneyanglan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Permutations II 解答相关的知识,希望对你有一定的参考价值。

Question

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

For example,
[1,1,2] have the following unique permutations:
[1,1,2][1,2,1], and [2,1,1]

Solution

Tricky here is to avoid duplicated solutions.

 1 public class Solution 
 2     public List<List<Integer>> permuteUnique(int[] nums) 
 3         Arrays.sort(nums);
 4         int length = nums.length;
 5         boolean[] visited = new boolean[length];
 6         List<List<Integer>> result = new ArrayList<List<Integer>>();
 7         
 8         dfs(nums, visited, new ArrayList<Integer>(), result);
 9         return result;
10     
11 
12     private void dfs(int[] nums, boolean[] visited, List<Integer> record, List<List<Integer>> result) 
13         if (record.size() == nums.length) 
14             result.add(new ArrayList<Integer>(record));
15             return;
16         
17         int prev = -1;        
18         for (int i = 0; i < nums.length; i++) 
19             if (visited[i])
20                 continue;
21             if (prev != -1 && nums[i] == nums[prev])
22                 continue;
23             record.add(nums[i]);
24             visited[i] = true;
25             dfs(nums, visited, record, result);
26             record.remove(record.size() - 1);
27             visited[i] = false;
28             prev = i;
29         
30     
31 

Python3

class Solution:
    def dfs(self, nums: List[int], visited: List[int], record: List[int], result: List[List[int]]) -> None:
        if (len(record) == len(nums)):
            if record not in result:
                result.append(copy.deepcopy(record))
            return
        for i in range(len(nums)):
            if visited[i]:
                continue
            # if previous node equals to current node, and previous one has not been visited, ignore dfs for current node.
            if i > 0 and nums[i] == nums[i - 1] and not visited[i - 1]:
                continue
            visited[i] = True
            record.append(nums[i])
            self.dfs(nums, visited, record, result)
            # revert status
            visited[i] = False
            record.pop()
    
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        result = []
        visited = [False] * len(nums)
        self.dfs(nums, visited, [], result)
        return result
        

 

以上是关于Permutations II 解答的主要内容,如果未能解决你的问题,请参考以下文章

[Lintcode]16. Permutations II/[Leetcode]47. Permutations II

LeetCode46,47 Permutations, Permutations II

leetcode 46-Permutations and 47-Permutations II

[Leetcode] Permutations II

#Leetcode# 47. Permutations II

LintCode : Permutations II