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.
Note:
- All numbers will be positive integers.
- The solution set must not contain duplicate combinations.
Example 1:
1 | Input: k = 3, n = 7 |
Example 2:
1 | Input: k = 3, n = 9 |
dfs
beginNumber从1到9依次判断
- 若含有beginNumber, 则需寻找所有的长度为k-1, 和为n-beginNumber的vector, 再从所有满足条件的vector上push_back(gebinNumber).
- 若不含有beginNumber, 则需要寻找所有长度为k, 和为n的vector
两个vector取并集即为所得
1 | class Solution { |
dfs2
贴一个我觉得更清晰的代码
1 | void dfs(int k, int sum, int idx, vector<int>& cur, vector<vector<int>>& ans) |