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.
Ensure that numbers within the set are sorted in ascending order.
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]]
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
這道題題是組合之和系列的第三道題,跟之前兩道 Combination Sum,Combination Sum II 都不太一樣,那兩道的聯系比較緊密,變化不大,而這道跟它們最顯著的不同就是這道題的個數是固定的,為k。個人認為這道題跟那道 Combinations 更相似一些,但是那道題只是排序,對k個數字之和又沒有要求。所以實際上這道題是它們的綜合體,兩者雜糅到一起就是這道題的解法了,n是k個數字之和,如果n小於0,則直接返回,如果n正好等於0,而且此時out中數字的個數正好為k,說明此時是一個正確解,將其存入結果res中,具體實現參見代碼入下:
class Solution { public: vector<vector<int> > combinationSum3(int k, int n) { vector<vector<int> > res; vector<int> out; combinationSum3DFS(k, n, 1, out, res); return res; } void combinationSum3DFS(int k, int n, int level, vector<int> &out, vector<vector<int> > &res) { if (n < 0) return; if (n == 0 && out.size() == k) res.push_back(out); for (int i = level; i <= 9; ++i) { out.push_back(i); combinationSum3DFS(k, n - i, i + 1, out, res); out.pop_back(); } } };
類似題目: