Subsets II
Given a collection of integers that might contain duplicates, Nums, return all possible subsets.
Note:
- Elements in a subset must is in non-descending order.
- The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,2]
, a solution is:
[ 2], [1], [1,2,2], [2,2], [up ], []]
The same idea on the previous question, plus to go heavy on it.
Http://www.cnblogs.com/Liok3187/p/4733079.html
Non-recursive:
1 /**2 * @param {number[]} nums3 * @return {number[][]}4 */5 varSubsetswithdup =function(nums) {6Nums =nums.sort (sorting);7 varres = [[]], arr = [], visited =NewSet ();8 for(vari = 0; i < nums.length; i++){9 if(!Visited.has (Nums[i])) {Ten Res.push ([nums[i]]); One Visited.add (Nums[i]); A } - Arr.push ({val: [nums[i]], pos:i}); - } the getsets (arr); - returnRes; - - functionGetsets (arr) { + varI, J, tmp, Nextarr = []; - for(i = 0; i < arr.length; i++){ + for(j = Arr[i].pos + 1; j < Nums.length; J + +){ ATMP = Arr[i].val.slice (0); at Tmp.push (Nums[j]); - if(!visited.has (Tmp.join (' # ')))){ - Res.push (TMP); -Visited.add (Tmp.join (' # '))); - } - Nextarr.push ({val:tmp, pos:j}); in } - } to if(Nextarr.length > 0){ + getsets (Nextarr); - } the } * $ functionsorting (A, b) {Panax Notoginseng if(A >b) { - return1; the}Else if(A <b) { + return-1; A}Else{ the return0; + } - } $};
Recursion:
1 /**2 * @param {number[]} nums3 * @return {number[][]}4 */5 varSubsetsWithDup2 =function(nums) {6Nums = Nums.sort (sorting), visited =NewSet ();7 varres = [];8 for(vari = 0; I < Math.pow (2, nums.length); i++){9 varstr =PadLeft (i, nums.length);Ten varTMP = []; One for(varj = 0; J < Str.length; J + +){ A if(Str[j] = = = ' 1 '){ - Tmp.push (Nums[j]); - } the } - if(!visited.has (Tmp.join (' # ')))){ - Res.push (TMP); -Visited.add (Tmp.join (' # '))); + } - } + returnRes; A at functionpadLeft (num, len) { - varres = "", I =Len; - while(i--) Res + = ' 0 '; - varTMP = parseint (num). toString (2); -res = res +tmp; - returnres.substring (Tmp.length, res.length); in } - to functionsorting (A, b) { + if(A >b) { - return1; the}Else if(A <b) { * return-1; $}Else{Panax Notoginseng return0; - } the } +};
[Leetcode] [JavaScript] Subsets II