Categories
Uncategorized

90. Subsets II Leetcode Javascript Solution

The Problem:

Given an integer array nums that may contain duplicates, return all possible subsets (the power set).

The solution set must not contain duplicate subsets. Return the solution in any order.

Example 1:

Input: nums = [1,2,2]
Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]

Example 2:

Input: nums = [0]
Output: [[],[0]]

Constraints:

  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10

The Solution:

var subsetsWithDup = function(nums) {
    let results = [],temp = []
    nums.sort((a,b) => a-b)
    console.log(nums)
    function backtrack(nums,start,results, temp){
        results.push([...temp])
       /* console.log("results " )
        for( rest of results){
            console.log(rest)
        }
        */
        for(let i = start; i < nums.length; i++){
               //console.log("i " + i)
               if(i == start || nums[i] != nums[i-1]){
//                 console.log("i after if" + i)
                temp.push(nums[i])
             //   console.log(temp)
                backtrack(nums,i+1,results,temp)
                temp.pop()
//                console.log("temp after pop " + temp)
                 }
        }
    }
    backtrack(nums,0,results,temp)
    return results
};

Leave a Reply

Your email address will not be published. Required fields are marked *