Leetcode 216. Combination Sum III 解題思路
阿新 • • 發佈:2018-12-21
題目:
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:
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]]
注意:這裡給的例子都是 k= 3 的情況,而 k 也可以取正整數。
每個值的範圍是[1, 9]
既然 k 是變數, 於是就可以採用遞迴的方法來寫。另外,按照升序來進行排序會簡單一些
程式碼如下:
vector<vector<int>> deepth(int k, int n, int begin) { if(k == 2 ) { vector<vector<int>> ans; int z = 0; for(int i = begin; i <= n / k && i <= 9; ++i) { z = n - i; if(z <= i) break; if(z < 10) ans.push_back(vector<int>{i, z}); } return ans; } else { vector<vector<int>> final; vector<vector<int>> tmp; vector<int> mid; for(int i = begin; i < n / k && i <= 9; ++i) { tmp = deepth(k - 1, n - i, i + 1); for(size_t j = 0; j < tmp.size(); ++j) { tmp[j].insert(tmp[j].begin(), i); } final.insert(final.end(), tmp.begin(), tmp.end()); tmp.clear(); } return final; } } vector<vector<int>> combinationSum3(int k, int n) { if(k == 1) { return vector<vector<int>>{vector<int>{1}}; } vector<vector<int>> ans = deepth(k, n, 1); return ans; }