MediumNo. 0077

Combinations — LeetCode 77 Python Solution

Topics
Backtracking
On a study list
Top Interview 150
Reading time
3 min

The problem

Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n]. You may return the answer in any order.

Example

Input
n = 4, k = 2
Output
[[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
Explanation
There are 4 choose 2 = 6 total combinations.

Python solution

PythonSolution
class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        def dfs(i: int):
            if len(t) == k:
                ans.append(t[:])
                return
            if i > n:
                return
            t.append(i)
            dfs(i + 1)
            t.pop()
            dfs(i + 1)

        ans = []
        t = []
        dfs(1)
        return ans

Complexity

Time
(C_nk × k)
Space · auxiliary
O(k)

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 77. Combinations is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0078SubsetsMedium
0079Word SearchMedium
0039Combination SumMedium
0040Combination Sum IIMedium
0046PermutationsMedium
0047Permutations IIMedium

Frequently asked questions

How hard is LeetCode 77. Combinations?

LeetCode 77. Combinations is rated Medium on LeetCode.

What is the time complexity of LeetCode 77. Combinations?

The Python solution on this page runs in (C_n^k \times k).

What is the space complexity of LeetCode 77. Combinations?

The Python solution on this page uses O(k) auxiliary space.

What topics does LeetCode 77. Combinations cover?

LeetCode 77. Combinations is tagged Backtracking on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.