码迷,mamicode.com
首页 > 其他好文 > 详细

Permutations II 解答

时间:2019-08-31 01:02:32      阅读:53      评论:0      收藏:0      [点我收藏+]

标签:following   append   ==   for   integer   return   void   def   follow   

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 解答

标签:following   append   ==   for   integer   return   void   def   follow   

原文地址:https://www.cnblogs.com/ireneyanglan/p/4884946.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!