[leetcode] 78. Subsets

불불이·2021년 2월 9일
0

매일 알고리즘

목록 보기
3/5

문제

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.


정답

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var subsets = function(nums) {
    
    let result = [[]];
    
    function backtracking(first, current) {
        for(let i = first; i<nums.length; i++) {
            current.push(nums[i]);
            result.push([...current]);
            backtracking(i+1, current);
            current.pop();
        }    
    }
    
    
    backtracking(0, [])
    return result;
};

핵심은 backtracking 할때 i+1 하여 전에 index와 중복되지 않게 하는 것!

profile
https://nibble2.tistory.com/ 둘 중에 어떤 플랫폼을 써야할지 아직도 고민중인 사람

0개의 댓글