Subsets
Given a set of distinct integers, 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,3] , a solution is:
[ 3], [1], [2], [1,3], [+] , [2,3], [up ], []]
All arranged.
First, the ingenious solution of non-recursion.
Examples of topics such as:
A total of 8 cases, if the three-bit binary representation, 1 for the election, 0 for the non-election, just 000 to 111.
The PadLeft method in the code converts the current number to a binary string of length equal to Nums.length, and the number of bits is less than 0.
1 /**2 * @param {number[]} nums3 * @return {number[][]}4 */5 varsubsets =function(nums) {6Nums =nums.sort (sorting);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 } - Res.push (TMP); - } - returnRes; + - functionpadLeft (num, len) { + varres = "", I =Len; A while(i--) Res + = ' 0 '; at varTMP = parseint (num). toString (2); -res = res +tmp; - returnres.substring (Tmp.length, res.length); - } - - functionsorting (A, b) { in if(A >b) { - return1; to}Else if(A <b) { + return-1; -}Else{ the return0; * } $ }Panax Notoginseng};
High efficiency.
The conventional recursive method.
More difficult to describe, lifting chestnuts [1,2,3,4]
When recursion is reached, the next round of recursion is [all-in-one] and [1,2,4].
[1,2,3,4] will be handed back to [the].
When recursive to [1,3], the next round of recursion is [1,3,4].
And so on
1 /**2 * @param {number[]} nums3 * @return {number[][]}4 */5 varsubsets =function(nums) {6Nums =nums.sort (sorting);7 varres = [[]], arr = [];8 for(vari = 0; i < nums.length; i++){9 Res.push ([nums[i]]);Ten Arr.push ({val: [nums[i]], pos:i}); One } A getsets (arr); - returnRes; - the functionGetsets (arr) { - varI, J, tmp, Nextarr = []; - for(i = 0; i < arr.length; i++){ - for(j = Arr[i].pos + 1; j < Nums.length; J + +){ +TMP = Arr[i].val.slice (0); - Tmp.push (Nums[j]); + Res.push (TMP); A Nextarr.push ({val:tmp, pos:j}); at } - } - if(Nextarr.length > 0){ - getsets (Nextarr); - } - } in - functionsorting (A, b) { to if(A >b) { + return1; -}Else if(A <b) { the return-1; *}Else{ $ return0;Panax Notoginseng } - } the}
[Leetcode] [JavaScript] Subsets