Post

Leetcode 77. Combinations

Explanation for Leetcode 77 - Combinations, and its solution in Python.

Problem

Leetcode 77 - Combinations

Example:

1
2
3
4
5
6
7
8
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.
Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.

Input: n = 1, k = 1
Output: [[1]]
Explanation: There is 1 choose 1 = 1 total combination.

Approach

We can use DFS to backtrack. If len(arr) == k, then we can append the array to res.

We can for loop x to n+1, and call dfs(i, arr). We can append arr before dfs then pop after calling dfs.

Here is the Python code for the solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]: 
        res = []

        def dfs(x, arr):
            if len(arr) == k:
                res.append(arr)
                return
            
            for i in range(x, n+1):
                arr.append(i)
                dfs(i+1, arr)
                arr.pop()
        
        dfs(1, [])
        return res

Time Complexity and Space Complexity

Time Complexity: $O(2^n)$

Space Complexity: $O(n)$

This post is licensed under CC BY 4.0 by the author.