题目
给出n和k,从1到9中选出k个数,使得k个数的和为n。1到9每个数只能使用1次。
Python题解
class Solution(object):
def combinationSum3(self, k, n):
"""
:type k: int
:type n: int
:rtype: List[List[int]]
"""
path, res = [], []
self.dfs(k, n, 1, path, res)
return res
def dfs(self, k, n, index, path ,res):
if k == 0:
if sum(path) == n:
res.append(path[:])
else:
for i in range(index, 10):
path.append(i)
self.dfs(k - 1, n, i + 1, path, res)
path.pop(-1)