Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Backtracking & Recursion/Subsets / Permutations / Combinations

Learn the pattern · ~15 min

Subsets / Permutations / Combinations

also called complete search, generate all

Walk the decision tree depth-first with one shared path: record it, then for each next choice choose, recurse, un-choose.

Signals'return all' subsets/permutations/combinationsn <= 10-20output size itself is exponential
Cheat sheet and practice

Reach for it when you read

  • +"Return all subsets / combinations / permutations" and n is small (about 20 or less).
  • +Every element is either in or out, and you need every choice, not just a count.
  • +Combinations of size k, or with a target sum, where elements may or may not be reused.
  • +The input has duplicates and each different answer must appear once.

Not this one when

  • ×Only the number of subsets with some sum: knapsack DP, not listing.
  • ×Choices that constrain each other (queens, grids, cutting rules): backtracking with pruning.
  • ×The best subset under a capacity with n in the hundreds: DP or greedy.

Learn Subsets / Permutations / Combinations

First, what is a subset?

A subset of [1, 2, 3] is any choice of some of its elements: none, some, or all. Order doesn't matter, so [1, 3] and [3, 1] are the same subset. Every element is either in or out, so 3 elements give 2 × 2 × 2 = 8 subsets: [] [1] [2] [3] [1, 2] [1, 3] [2, 3] [1, 2, 3].

A combination is a subset of fixed size k. A permutation is an arrangement where order does matter: [1, 3] and [3, 1] differ.

All three are built by one recursive function that grows a shared list, path.

How do we list every subset once?

Picture a tree whose root is the empty subset. Each call records its path, then tries one more element. The rule:

Record path. Then for every element after the last one picked: add it, go one level deeper, take it out again.

"After the last one picked" stops repeats: once you've picked 2, you never go back and add 1, so [2, 1] is never built.

On [1, 2, 3] (the number in dfs(i) is where the next pick may start):

call path recorded what happens next
dfs(0) [] try 1, then 2, then 3
dfs(1) [1] try 2, then 3
dfs(2) [1, 2] try 3
dfs(3) [1, 2, 3] nothing after 3: go back up, remove 3, then 2
dfs(3) [1, 3] nothing after 3: back up to []
dfs(2) [2] try 3
dfs(3) [2, 3] nothing after 3: back up
dfs(3) [3] nothing after 3: done

Eight calls, eight subsets, each once.

The code for it

C++
void dfs(const vector<int>& nums, int start) {
    res.push_back(path);                       // every call is one subset: record it
    for (int i = start; i < (int)nums.size(); i++) {
        path.push_back(nums[i]);               // choose
        dfs(nums, i + 1);                      // explore: only later elements
        path.pop_back();                       // un-choose
    }
}

You don't need to memorise this. It's the table: record, then for each later element, choose, go deeper, un-choose.

Why pop_back() after the call? Because path is shared. When dfs(2) with [1, 2] returns, the loop's next try is 3, and it must start from [1], not [1, 2]. Taking 2 out puts path back where it was.

Fine, but how does this help us?

The classic step up: Subsets II. The input can have equal values, and each different subset must appear once. Run the tree above by hand on [1, 2, 2] (the indices say which copy of 2 was used):

indices picked subset new?
none [] yes
0 [1] yes
0, 1 [1, 2] yes
0, 1, 2 [1, 2, 2] yes
0, 2 [1, 2] no: the same as 0, 1
1 [2] yes
1, 2 [2, 2] yes
2 [2] no: the same as 1

So the answer is [] [1] [1, 2] [1, 2, 2] [2] [2, 2]: six, not eight.

The brute force

Build all 2ⁿ picks, sort each so equal subsets look the same, let a set drop repeats.

C++
vector<vector<int>> subsetsBrute(const vector<int>& nums) {
    int n = nums.size();
    set<vector<int>> seen;
    for (int mask = 0; mask < (1 << n); mask++) {          // all 2^n ways to pick
        vector<int> s;
        for (int i = 0; i < n; i++)
            if (mask >> i & 1) s.push_back(nums[i]);
        sort(s.begin(), s.end());                          // [2,1] and [1,2] look the same
        seen.insert(s);                                    // the set drops repeats
    }
    return vector<vector<int>>(seen.begin(), seen.end());
}

It's correct, but it throws most of its work away. With twenty 2s it builds 2²⁰ = 1,048,576 subsets, sorts each, checks each against the set, and keeps 21. At LeetCode's n ≤ 10 it still passes; the waste is what we fix.

The one thought that fixes it

Sort first, so equal values sit side by side: [1, 2, 2]. Stop at the root, dfs(0). Its loop is about to try 2 at index 1, then 2 at index 2.

  • Picking index 1 starts a subtree that holds [2] and [2, 2].
  • Picking index 2 starts a subtree that holds only [2].

The first subtree already builds everything the second does: from index 1 you can still reach index 2. So at the same level, an equal value right after one you've tried adds nothing. Skip it.

One level deeper is different. Inside index 1's subtree the path is [2] and the loop starts at index 2. Taking the second 2 there builds [2, 2], which is new. So the skip applies only to a loop's later picks, never its first. That's what i > start says:

C++
void dfs(const vector<int>& nums, int start) {             // nums is sorted
    res.push_back(path);
    for (int i = start; i < (int)nums.size(); i++) {
        if (i > start && nums[i] == nums[i - 1]) continue; // same level, same value: skip
        path.push_back(nums[i]);
        dfs(nums, i + 1);
        path.pop_back();
    }
}

Dry run

Sorted [1, 2, 2], with the skip:

call path recorded tries skips
dfs(0) [] 1, then 2 (index 1) 2 (index 2): equal to the 2 just tried
dfs(1) [1] 2 (index 1) 2 (index 2), same reason
dfs(2) [1, 2] 2 (index 2): first pick of this level, allowed none
dfs(3) [1, 2, 2] none none
dfs(2) [2] 2 (index 2): first pick of this level, allowed none
dfs(3) [2, 2] none none

[] [1] [1, 2] [1, 2, 2] [2] [2, 2], the same answer as the brute force, and the repeated subtrees are never entered.

Write i > 0 instead of i > start and the deeper first picks get skipped too: the output loses [1, 2, 2] and [2, 2].

Why it's O(2ⁿ · n)

Count the work at each node: one subset is recorded, and copying path costs up to n. There are at most 2ⁿ nodes, one per subset, so O(2ⁿ · n) time; with duplicates, only the different subsets get a node. Depth and path are at most n: O(n) extra space, plus the output.

You can't beat 2ⁿ when you must print 2ⁿ subsets. The skip saves the work on copies.

Order matters? Permutations and used[]

For permutations, any unused element can go next, even one to the left. So the loop starts at 0 every time, a used[] array marks what's in the path, and only full-length paths are recorded.

With equal values (sorted), [1, 1, 2] gives six paths but only three different orders: the two 1s swap and build the same thing twice. The fix:

C++
if (used[i]) continue;                                           // already in the path
if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue;   // left twin not placed yet

So equal copies are always placed left to right: the second 1 may go in only once the first 1 is in the path, and "second 1, first 1" is never built.

path so far tries skips
[] 1 (index 0), 2 1 (index 1): its twin, index 0, isn't placed
[1] 1 (index 1), 2 none: index 0 is placed
[1, 1] 2 → [1, 1, 2]
[1, 2] 1 (index 1) → [1, 2, 1]
[2] 1 (index 0) 1 (index 1)
[2, 1] 1 (index 1) → [2, 1, 1]

Three permutations, each once. (used[i - 1] without the ! also builds each order once, but prunes later: on [1, 1, 1, 2, 2, 2, 3] it makes 1,934 calls instead of 448.)

Combinations of size k? Record only full paths

Keep the start index; record a path only when it's full:

C++
if ((int)path.size() == k) { res.push_back(path); return; }   // record only full ones

From [1, 2, 3, 4] with k = 2 that gives [1, 2] [1, 3] [1, 4] [2, 3] [2, 4] [3, 4].

Each number reusable? Recurse with i

Combination Sum: pick numbers that add up to a target, each usable many times. Carry what's left, record the path at 0, skip numbers bigger than what's left, and stay on the same index:

C++
dfs(c, i, left - c[i]);                // i, not i + 1: c[i] may be used again

[2, 3, 6, 7] with target 7 gives [2, 2, 3] and [7].

Remember this

  • "All subsets / combinations / arrangements", n up to about 20 (about 10 for arrangements): this tree.
  • Next call on i + 1: each element once. On i: reuse allowed. Loop from 0 with used[]: order matters.
  • Duplicates: sort first, then skip with i > start for subsets, or !used[i - 1] for permutations.
  • Always undo what you did before the call, or the next branch starts from a dirty path.

Practise it on Subsets, then Combinations (fixed size), Permutations (order matters), Subsets II (the same-level skip), Combination Sum (reuse with a target) and Permutations II (the used[i - 1] rule).

Below, watch Subsets run line by line.

Watch it work, line by line

Subsets ↗, nums = [1, 2, 3] → [], [1], [1,2], [1,2,3], [1,3], [2], [2,3], [3]. Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 4 times it stops to ask you what happens next.

Loading the walkthrough…

When to use it, and when not

Ask yourself

Do they want every subset, combination or ordering (not a count, not the best one), and is n small enough (about 20 for sets, 10 for orderings) that the whole output fits?

Reach for it when

  • +'return all' subsets/permutations/combinations
  • +n <= 10-20
  • +output size itself is exponential
  • +n <= 20 for subsets (2n), n <= 8-10 for permutations (n!)

It fails when

  • ×Only the count of ways or the single best is askeduse DP or greedy, not enumeration
  • ×n is large (≥ ~25), so 2ⁿ is hopelessuse Find structure: DP or math
  • ×A goal must be satisfied incrementally with heavy pruninguse Prune-as-you-go backtracking

Looks like it, isn't (and the other way round)

  • Combination Sum IV looks like Subsets / Permutations / Combinations, needs Unbounded Knapsack

    Only the count is asked and order matters: dp over amounts with amount as outer loop.

  • Find the K-Sum of an Array looks like Subsets / Permutations / Combinations, needs K-way Merge

    Enumerating subsets is 2n. Sort |a| and pop k times from a frontier heap with the 'extend / replace last' successor rule.

Recall card

Answer each one out loud before you open it. Come back in three days and try again without reading the page.

  • 1Why does the subsets loop start at start and not at 0?Reveal

    So each subset is built in one order only (increasing index). [2, 1] never appears after [1, 2].

  • 2Why pop_back() right after the recursive call?Reveal

    To undo the choice. The next sibling must start from the same path, or choices leak between branches.

  • 3Subsets II: why skip nums[i] == nums[i - 1] only when i > start?Reveal

    Equal values at the same level make the same branch twice. At different depths they're different subsets, like [2, 2].

Practice ladder

every problem →
  1. 1Subsetsthe hookMedium
  2. 2Combinationsfixed size kMedium
  3. 3Permutationsorder mattersMedium
  4. 4Subsets IIduplicatesMedium
  5. 5Combination Sumreuse with a targetMedium
  6. 6Letter Combinations of a Phone Numberone list per positionMedium
  7. 7Permutations IIorder and duplicatesMedium
  8. 8Apple Divisionbest over all subsetsEasy

Finished Subsets / Permutations / Combinations? Mark it done and Lessgo moves you to the next step.

Start the climb9 steps from E-Rank to S, with a coachPractise itthe cheat sheet and every problem, easy to OA level
Back to Subsets / Permutations / Combinations

On this page

The lessonWatch it workThe templateWhen to use itRecallPractice ladder
TodayReviewPatternsProblems

The template: frame and slot · every line explained, then clean C++, Java and Python to revise from

Start the free 7-day trial