由于之前已经做过全排列,所以这个题就很简单了——在全排列的基础上去掉重复的即可。我是用hashSet排除重复的。
public class Solution {
public IList<IList<int>> PermuteUnique(int[] nums) {
List<IList<int>> res = new List<IList<int>>();
HashSet<int> hs = new HashSet<int>();
for (int i = 0; i < nums.Length; i++)
{
if(hs.Contains(nums[i]))
continue;
hs.Add(nums[i]);
IList<IList<int>> list = new List<IList<int>>();
if (nums.Length == 1)
{
list.Add(new List<int>());
}
else
{
int[] tmp = new int[nums.Length - 1];
int j = 0;
int k = 0;
while (j < nums.Length)
{
if (j == i)
{
j++;
}
else
{
tmp[k++] = nums[j++];
}
}
list = PermuteUnique(tmp);
}
for (int l = 0; l < list.Count(); l++)
{
list[l].Add(nums[i]);
}
res.AddRange(list);
}
return res;
}
}