Algo-Sim › Recursion & Backtracking

Subsets

Medium · Recursion & Backtracking · step through it in Java, Python and C++ on your own input

Return every subset of distinct numbers using choose / explore / unchoose backtracking.

Problem

Given an array nums of distinct integers, return every possible subset (the power set), including the empty set and nums itself. The order of the subsets does not matter.

Constraints

Edge cases to test

Follow-up questions

How else can you enumerate subsets?
Count from 0 to 2ⁿ − 1 and take the bits of each mask: O(n·2ⁿ) without recursion.
What if there are duplicates?
Sort and skip a value equal to the previous one at the same depth (LC 90).

Solution

Java

List<List<Integer>> result = new ArrayList<>();

List<List<Integer>> subsets(int[] nums) {
    backtrack(nums, 0, new ArrayList<>());
    return result;
}

void backtrack(int[] nums, int start, List<Integer> path) {
    result.add(new ArrayList<>(path));
    for (int i = start; i < nums.length; i++) {
        path.add(nums[i]);
        backtrack(nums, i + 1, path);
        path.remove(path.size() - 1);
    }
}

Python

def subsets(nums):
    result = []

    def backtrack(start, path):
        result.append(path[:])
        for i in range(start, len(nums)):
            path.append(nums[i])
            backtrack(i + 1, path)
            path.pop()

    backtrack(0, [])
    return result

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<vector<int>> result = {};

    vector<vector<int>> subsets(vector<int> &nums) {
        vector<int> path;
        backtrack(nums, 0, path);
        return result;
    }

    void backtrack(vector<int> &nums, int start, vector<int> &path) {
        result.push_back(path);
        for (int i = start; i < int(nums.size()); i++) {
            path.push_back(nums[i]);
            backtrack(nums, i + 1, path);
            path.pop_back();
        }
    }
};

More Recursion & Backtracking problems