题目:
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:
[[1,2,4]]
Example 2:
Input: k = 3, n = 9
Output:
[[1,2,6], [1,3,5], [2,3,4]]
思路:
这是一道典型的Backtracking的题目,其实大家有没有发现它在实现上就是DFS?另外,由于要求出所有符合条件的解,所以我们会用到Backtracking的技术。思路就是:一旦发现符合题目要求的解,就把它添加到结果集合中。否则我们就让i从start + 1循环到9,尝试把i放在解中,并进行深度搜索。当然在循环的内部别忘了回溯(否则找不到所有的解)^_^。建议读者对这类题目设计一个实现模板。
代码:
class Solution {
public:
vector<vector<int>> combinationSum3(int k, int n) {
vector<vector<int>> results;
vector<int> line;
combinationSum3(results, line, k, n, 0, 0);
return results;
}
private:
void combinationSum3(vector<vector<int>>& results, vector<int> &line, int k, int n, int start, int sum) {
if (sum >= n || line.size() >= k) {
if (sum == n && line.size() == k) {
results.push_back(line);
}
return;
}
for (int i = start + 1; i <= 9; ++i) {
line.push_back(i); // try to add the i
combinationSum3(results, line, k, n, i, sum + i);
line.pop_back();
}
}
};