1. 程式人生 > >[LeetCode] Combination Sum III 組合之和之三

[LeetCode] Combination Sum III 組合之和之三

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(); } } };

類似題目: