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]]
分析: n是k個不同的個位數之和,即1~9每個數字有2種選擇,選或不選(兩種遞歸) 。 採用深度搜索,如果不選該數即繼續往下遞歸,如果選了該數,n減掉該數,k減1,繼續往下遞歸。class Solution {
public:
vector<vector<int>> combinationSum3(int k, int n) {
vector<int> p;
vector<vector<int>> ans;
DFS(k, n, 1, p, ans);
return ans;
}
void DFS(int k, int n, int cur, vector<int>& p, vector<vector<int>>& ans) {
if (k==0) {
if (n == 0) ans.push_back(p);//p滿足加入答案
return;
}
if (cur > 9) return; //此處不能放在k==0之前,如果放在k==0之前當答案含有9的時候會跳過該答案直接返回
DFS(k, n, cur+1, p, ans); //不選cur
p.push_back(cur); //選擇cur
DFS(k-1, n-cur,cur+1, p, ans);
p.pop_back(); //深搜完把cur pop掉
}
};