Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
Example 1:
Input: k = 3, n = 7
Output:
Example 2:
Input: k = 3, n = 9
Output:
解法1:
典型的backtracking的题目,用一般的模板就能解决。用一个helper函数,用一个数保存当前试的数的起始位置, 用一个vector存储当前选出的答案。
要注意的是退出条件。 同时注意到由于存在可能计算重复的数据,所以memorization可以帮助efficiency,不过下面的答案没有用。
C++
Java