본문 바로가기
CS/algorithm

[LeetCode] 78. Subsets

by 빠니몽 2024. 1. 29.

01.29.2024

1. Problem

2. My code

var subsets = function(nums) {
    let result = [];

    for(let i=0; i<nums.length; i++){
        result.push([nums[i]]);
        let tempArr = [];

        for(let j=0; j<result.length-1; j++){
            tempArr.push(result[j].concat(result[result.length-1]));
        }

        result.push(...tempArr);
    }
    result.push([]);
    return result;
};

Runtime: 70ms

Percentage: 14%

 

I felt the need to study more about javascript Set and the usage of it.

3. Better Performance

Since my code beats only 14 percent of JS users, I looked up some with better performance and am going to introduce one.

var subsets = function(nums) {
    let res = [[]], appendarr= [];
    
    for(let num of nums){
        appendarr = [];
        for(let entry of res){
            appendarr.push([...entry, num]);
        }
        
        res.push(...appendarr);
    }
    
    return res;
};

Runtime: 56ms

Percentage: 65%

 

This code has very similar algorithm to mine yet better performance and readibility.

I hope there will be a chance to try for ... of statement.