*leetcode46 47
2020-07-20 本文已影响0人
Hana_r
- leetcode46
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();
}
}
- leetcode47
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;
}
}