var permute = function(nums) {
let res=[];
let result=[];
backtrack(nums,result,res);
return res;
};
var backtrack=function(nums,result,res)
{
if(result.length==nums.length)//结束条件
{
res.push(result.slice());
return;
}
for(let i=0;i<nums.length;i++)
{
if(result.includes(nums[i]))//排除选过的
continue;
result.push(nums[i]);
backtrack(nums,result,res);
result.pop();
}
}
var permuteUnique = function(nums) {
let res=[];
let result=[];
let used=[];
nums.sort();
permute(nums,result,used,res);
return res;
};
var permute=function(nums,result,used,res)
{
if(nums.length==result.length)
{
res.push(result.slice());
return;
}
for(let i=0;i<nums.length;i++)
{
if(used[i]) continue;
if(i>0 && nums[i] == nums[i-1] && used[i-1]) break;
result.push(nums[i]);
used[i]=true;
permute(nums,result,used,res);
result.pop();
used[i]=false;
}
}
网友评论