Advertisement
jinhuang1102

77. Combinations

Nov 11th, 2018
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.57 KB | None | 0 0
  1. def backtrackComb(n, k, idx, temp, res):
  2.     # terminal condition
  3.     if len(temp) == k:
  4.         res.append(temp)
  5.         return
  6.     # recursive call
  7.     for i in range(idx, n + 1): #由于在python中的 for loop 是“左闭右开”区间,所以这里要用n+1
  8.         backtrackComb(n, k, i + 1, temp + [i], res)
  9.     return
  10.  
  11.  
  12. def combine(n, k):
  13.     """
  14.    :type n: int
  15.    :type k: int
  16.    :rtype: List[List[int]]
  17.    """
  18.     res = []
  19.     # 这道题 n 所代表的是 [1,2,3, ..., n], 所以遍历要从1开始
  20.     backtrackComb(n, k, 1, [], res)
  21.     return res
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement