Created
November 21, 2024 06:47
-
-
Save sAVItar02/c37aa8cd7e1e6eaa6404e9e29bd79420 to your computer and use it in GitHub Desktop.
Subsets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number[]} nums | |
* @return {number[][]} | |
*/ | |
var subsets = function(nums) { | |
let temp = []; | |
let res = []; | |
function rec(nums, i = 0) { | |
if(i === nums.length ) return res.push([...temp]); | |
temp.push(nums[i]); | |
rec(nums, i + 1); | |
temp.pop(); | |
rec(nums, i + 1); | |
} | |
rec(nums, 0); | |
return res; | |
}; | |
// make a recursive function that run from 0 to length of nums | |
// at each num we have a choice to choose that num or not choose it | |
// if we choose if, we push it in temp array and move on to the next num | |
// if we dont choose it, we remove it from the temp array and carry on to the next element | |
// keep doing this till we hit the last element | |
// push whatever we have in temp into res array (Base case) | |
// Time: O(2^n) | |
// Space: O(n) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment