46. Permutations(js)
46. Permutations
Given a collection of distinct integers, return all possible permutations.
Example:
Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]
题意:找出数组所有不重复的排列组合
代码如下:
/** * @param {number[]} nums * @return {number[][]} */ var permute = function(nums) { var res=new Set(); var curr=new Set(); backtrack(res,curr,nums) return [...res]; }; var backtrack=function(res,curr,nums){ if(nums.length===curr.size){ res.add([...curr]); }else{ for(var i=0;i<nums.length;i++){ if(curr.has(nums[i])) continue; curr.add(nums[i]); backtrack(res,curr,nums); curr.delete(nums[i]); } } }