# 47. Permutations II 全排列 II

@TOC

## # 题目描述

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],
[2,1,1]
]
``````

## # 解题方法

### # 方法一：递归

``````class Solution(object):
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
self.helper(nums, res, [])
return res

def helper(self, nums, res, path):
if not nums and path not in res:
res.append(path)
else:
for i in range(len(nums)):
self.helper(nums[:i] + nums[i+1:], res, path + [nums[i]])
``````

### # 方法二：回溯法

C++代码如下:

``````
class Solution {
public:
vector<vector<int>> permuteUnique(vector<int>& nums) {
const int N = nums.size();
sort(nums.begin(), nums.end());
vector<bool> visited(N, false);
vector<vector<int>> res;
helper(nums, res, {}, visited, 0);
return res;
}
void helper(vector<int>& nums, vector<vector<int>>& res, vector<int> path, vector<bool>& visited, int count) {
if (count == nums.size()) {
res.push_back(path);
return;
}
for (int i = 0; i < nums.size(); i++) {
if (visited[i]) continue;
if (i > 0 && nums[i] == nums[i - 1] && !visited[i - 1]) continue;
visited[i] = true;
path.push_back(nums[i]);
helper(nums, res, path, visited, count + 1);
path.pop_back();
visited[i] = false;
}
}
};
``````

## # 日期

2018 年 3 月 10 日 2018 年 12 月 21 日 —— 一周就要过去了