77. Combinations
Medium
Problem:
Given a total number n, return all combinations of k elements.
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.
https://leetcode.com/problems/combinations/
Solution:
Backtracking
Start the next number from the last number in the current list: Instead of always starting from 1, you can start from the next number after the last number in the current list. This way, you avoid generating duplicate combinations.
Early stopping: If there are not enough numbers left to reach a total of
k
numbers, you can stop early. For example, ifn = 5
,k = 3
, and the current list is[4]
, there's no way to pick 3 numbers, so you can stop.
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
result = []
def dfs(start, cur):
# If the current list has k numbers, add it to the result
if len(cur) == k:
result.append(cur[:])
return
# If there are not enough numbers left to reach k, stop
if len(cur) + (n - start + 1) < k:
return
for i in range(start, n+1):
cur.append(i)
dfs(i+1, cur)
cur.pop()
dfs(1, [])
return result
itertools Module
Reference: itertools Module
import itertools
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
return list(itertools.combinations(range(1, n+1), k))
Last updated