본문 바로가기

리트코드/midium

[리트코드] 78. Subsets - js

반응형

1. 문제

https://leetcode.com/problems/subsets/description/

 

Subsets - LeetCode

Can you solve this real interview question? Subsets - 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.   Example 1: Input: n

leetcode.com

2. 코드

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var subsets = function(nums) {
    let answer = [];

    const dfs = (fixed, left) => {
        if(!answer.includes(fixed)) answer.push(fixed);
        for(let i=0;i<left.length;i++){
              if(!fixed.length || left[i] > fixed[fixed.length-1]){
                let newFixed = [...fixed,left[i]];
                let newLeft = left.slice();
                newLeft.splice(i,1);
                dfs(newFixed,newLeft);
              } 
          }
    }

    dfs([],nums);

    return answer.sort((a,b) => a.length-b.length);
};
반응형