给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。
示例 1:
输入:nums = [1,1,2]
输出:
[[1,1,2],
[1,2,1],
[2,1,1]]
示例 2:
输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
提示:
- 1 <= nums.length <= 8
- -10 <= nums[i] <= 10
1.回溯+暴力
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
res = []
flag = [True for i in range(len(nums))]
def dfs(nums, temp):
if len(temp) == len(nums):
result = deepcopy(temp)
if result not in res:
res.append(result)
for i in range(len(nums)):
if flag[i]:
temp.append(nums[i])
flag[i] = False
dfs(nums, temp)
temp.pop()
flag[i] = True
dfs(nums, [])
return res
2.排序+剪枝
Python:
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
res = []
flag = [True for i in range(len(nums))]
nums.sort()
def dfs(nums, temp, j):
if j == len(nums):
res.append(deepcopy(temp))
for i in range(len(nums)):
if not flag[i]:
continue
if i > 0 and nums[i] == nums[i-1] and flag[i-1]:
continue
temp.append(nums[i])
flag[i] = False
dfs(nums, temp, j+1)
temp.pop()
flag[i] = True
dfs(nums, [], 0)
return res
Java:
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
int[] flag = new int[nums.length];
Arrays.sort(nums);
List<Integer> arr = new ArrayList<Integer>();
backtrace(result, flag, nums, arr);
return result;
}
public void backtrace(List<List<Integer>> result, int[] flag, int[] nums, List<Integer> b)
{
if(b.size() == nums.length)
{
result.add(new ArrayList<Integer>(b));
}
for(int i = 0; i < nums.length; i++)
{
if(flag[i] == 0)
{
if( i > 0 && nums[i-1] == nums[i] && flag[i-1] == 0)
continue;
else
{
flag[i] = 1;
b.add(nums[i]);
backtrace(result, flag, nums, b);
b.remove(b.size()-1);
flag[i] = 0;
}
}
}
}
}
留言