[JS] Subsets
2022. 8. 24. 16:58
🔒 문제 (LeetCode 78)
Given an integer array nums of unique elements, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
Constraints:
- 1 <= nums.length <= 10
- -10 <= nums[i] <= 10
- All the numbers of nums are unique.
🌊 입출력
Example 1:
Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Example 2:
Input: nums = [0]
Output: [[],[0]]
🔑 해결
🌌 알고리즘 - DFS (조합)
/**
* @param {number[]} nums
* @return {number[][]}
*/
var subsets = function(nums) {
const result = [];
const len = nums.length;
const dfs = (route, index) => {
result.push(route)
if(route.length === len) {
return;
}
for(let i = index; i < len; i++) {
dfs([...route, nums[i]], i + 1);
}
}
dfs([], 0);
return result;
};
'코딩테스트 (JS) > DFS | BFS' 카테고리의 다른 글
[JS] Permutations II (0) | 2022.08.31 |
---|---|
[JS] Subsets II (0) | 2022.08.28 |
[JS] All Paths From Source to Target (0) | 2022.08.24 |
[JS] Shortest Path in Binary Matrix (0) | 2022.08.18 |
[JS] Subtree of Another Tree (0) | 2022.08.13 |