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
- 1 ≤ nums.length ≤ 10
- -10 ≤ nums[i] ≤ 10
- All values are distinct
- There are 2ⁿ subsets
Edge cases to test
- Empty input:
[[]] - One element
- Negative values (order of output may differ)
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 resultC++
#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
- Fibonacci Number (Easy)
- Tower of Hanoi (Medium)
- Generate Parentheses (Medium)
- Subsets II (Medium)
- Permutations (Medium)
- Permutations II (Medium)
- Combinations (Medium)
- Letter Combinations of a Phone Number (Medium)
- Combination Sum (Medium)
- Combination Sum II (Medium)
- Palindrome Partitioning (Medium)
- Restore IP Addresses (Medium)
- Word Break II (Hard)
- Remove Invalid Parentheses (Hard)
- Word Search (Medium)
- N-Queens (Hard)
- Sudoku Solver (Hard)