Skip to content
On this page

78. Subsets share

Problem Statement

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: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

Example 2:

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

ย 

Constraints:

  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10
  • All the numbers ofย nums are unique.

Solution:

go
package main

func subsets(nums []int) [][]int {
	res := make([][]int, 0)
	curr_subset := make([]int, 0)

	var backtrack func(i int)

	backtrack = func(i int) {
		println(i)
		if i >= len(nums) {
			curr_dup := make([]int, len(curr_subset))
			copy(curr_dup, curr_subset)
			res = append(res, curr_dup)
			return
		}

		// include the current element
		curr_subset = append(curr_subset, nums[i])
		backtrack(i + 1)

		// exclude the current element
		curr_subset = curr_subset[:len(curr_subset)-1] // pop the last element
		backtrack(i + 1)
	}

	backtrack(0)

	return res
}

py
class Solution:
    def subsets(self, nums: list[int]) -> list[list[int]]:
        res, curr = [], []

        def backtrack(i: int) -> None:
            if i >= len(nums):
                print(curr.copy())
                res.append(curr.copy())
                return

            # include the current element
            curr.append(nums[i])
            backtrack(i + 1)

            # exclude the current element
            curr.pop()
            backtrack(i + 1)

        backtrack(0)

        return res

...


Released under the MIT License.