# 题目描述

## 样例1

输入：[1,1]

[
[1,1]
]


## 样例2

输入：[1,2,2]

[
[1,2,2],
[2,1,2],
[2,2,1]
]


# 解题思路

Arrays.sort(nums) 			// 排序这样所有重复的数
if (i > 0 && nums[i] == nums[i - 1] && !visited[i - 1]) { continue; } 	// 跳过会造成重复的情况


# java题解

public class Solution {
/*
* @param :  A list of integers
* @return: A list of unique permutations
*/
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> results = new ArrayList<>();
if (nums == null) {
return results;
}

Arrays.sort(nums);
dfs(nums, new boolean[nums.length], new ArrayList<Integer>(), results);

return results;
}

private void dfs(int[] nums,
boolean[] visited,
List<Integer> permutation,
List<List<Integer>> results) {
if (nums.length == permutation.size()) {
return;
}

for (int i = 0; i < nums.length; i++) {
if (visited[i]) {
continue;
}
if (i > 0 && nums[i] == nums[i - 1] && !visited[i - 1]) {
continue;
}

visited[i] = true;
dfs(nums, visited, permutation, results);
visited[i] = false;
permutation.remove(permutation.size() - 1);
}
}
};


# C++题解

class Solution {
private:
void helper(vector<vector<int> > &results,
vector<int> &permutation,
vector<int> &nums,
bool used[]) {
if (nums.size() == permutation.size()) {
results.push_back(permutation);
return;
}

for (int i = 0; i < nums.size(); i++) {
if (used[i]) {
continue;
}
if (i > 0 && used[i - 1] == false && nums[i] == nums[i-1]) {
continue;
}

used[i] = true;
permutation.push_back(nums[i]);
helper(results, permutation, nums, used);
permutation.pop_back();
used[i] = false;
}
}

public:
vector<vector<int> > permuteUnique(vector<int> &nums) {
vector<vector<int> > results;
vector<int> permutation;
bool used[nums.size()];

for (int i = 0; i < nums.size(); i++) {
used[i] = false;
}

sort(nums.begin(), nums.end());

helper(results, permutation, nums, used);
return results;
}
};


# python题解

class Solution:
"""
@param nums: A list of integers.
@return: A list of unique permutations.
"""
def permuteUnique(self, nums):
def _permute(result, temp, nums):
if nums == []:
result += [temp]
else:
for i in range(len(nums)):
if i > 0 and nums[i] == nums[i-1]:
continue
_permute(result, temp + [nums[i]], nums[:i] + nums[i+1:])
if nums is None:
return []

if len(nums) == 0:
return [[]]

result = []
_permute(result, [], sorted(nums))
return result


©️2019 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客