↻one more pass.
Backtracking · Medium

Subsets: the idea to remember.

Return all subsets of an array of distinct integers, including the empty subset.

Solve on LeetCode ↗

The core insight

Branch on including or excluding each value and copy the current path when recording a subset.

Why it works

Every subset corresponds to a unique sequence of include or exclude decisions.

The mistake to avoid

Store a copy of the path; storing its mutable reference makes results change during backtracking.

Time: O(n · 2^n), including outputSpace: O(n) auxiliary; O(n · 2^n) output

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

// Java reference adapted from neetcode-gh/leetcode (MIT).
// Branch on including or excluding each value and copy the current path when recording a subset.
public List<List<Integer>> subsets(int[] nums) {
    List<List<Integer>> ans = new ArrayList<>();
    List<Integer> list = new ArrayList<>();
    helper(ans, 0, nums, list);
    return ans;
}

public void helper(
    List<List<Integer>> ans,
    int start,
    int[] nums,
    List<Integer> list
) {
    if (start >= nums.length) {
        ans.add(new ArrayList<>(list));
    } else {

        list.add(nums[start]);
        helper(ans, start + 1, nums, list);

        list.remove(list.size() - 1);
        helper(ans, start + 1, nums, list);
    }
}

Java reference adapted from neetcode-gh/leetcode · MIT license

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.