1. Combinations (Leetcode Number: 669)
The following code could be optimized when the value of k increases to avoid increasing time complexity.
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
res = []
sub_res = []
def backtrack(n, k, start_id):
if len(sub_res) == k:
# The colon has to be concluded, otherwise cause error
res.append(sub_res[:])
return
for i in range(start_id, n + 1):
sub_res.append(i)
backtrack(n, k, i + 1)
sub_res.pop()
backtrack(n, k, 1)
return res