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]]
思路:
组合问题,递归,1-9 每个数字都分放入和不放入两种情况。得到满足条件的就压入答案。
class Solution { public: vector<vector<int>> combinationSum3(int k, int n) { vector<int> partans; vector<vector<int>> ans; combination(1, k, n, partans, ans); return ans; } void combination(int curNum, int k, int sum, vector<int> &partans, vector<vector<int>> &ans) { if(curNum > 10 || sum < 0 || k < 0) return; //注意这里是 > 10, 否则数字9的答案无法压入 if(sum == 0 && k == 0) { ans.push_back(partans); } else { partans.push_back(curNum); combination(curNum + 1, k - 1, sum - curNum, partans, ans); partans.pop_back(); combination(curNum + 1, k, sum, partans, ans); } } };
时间: 2024-10-12 23:53:20