Skip to main content

Subsets

This technique uses backtracking to find subsets in an input data.

How to Identify

  • Data Structure Involves: Array, String
  • Question Type: When you need to find the subsets of a given set.

Example

Subsets problem

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
Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Typescript
function subsets(nums: number[]): number[][] {
const result: number[][] = []

function backtracking(start: number, subset: number[]){
result.push(subset.slice())

for(let i = start; i < nums.length; i++){
subset.push(nums[i])
backtracking(i+1, subset)
subset.pop()
}
}

backtracking(0, [])
return result
};
ProblemsDifficulty
1SubsetsMedium
2Subsets IIMedium