数字选取[1-9]
不重复
这个题类似于LC77.组合,组合的问题是非重复的,这个题也是非重复的,这个题只是多了个求和。
class Solution(object):
def combinationSum3(self, k, n):
"""
:type k: int
:type n: int
:rtype: List[List[int]]
"""
# 回溯法
result = list()
self.backtracking(k, n, result, 1, [])
return result
def backtracking(self, k, n, result, start, path):
# 剪枝
if sum(path) > n:
return
# 终止条件
if len(path) == k and sum(path) == n:
result.append(path[:])
return
for i in range(start, 10):
path.append(i)
self.backtracking(k, n, result, i+1, path)
path.pop()