Combination Sum III问题及解法

来源:互联网 发布:内网软件 编辑:程序博客网 时间:2024/05/18 02:29

问题描述:

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.

示例:

Input: k = 3, n = 7

Output:

[[1,2,4]]


Input: k = 3, n = 9

Output:

[[1,2,6], [1,3,5], [2,3,4]]

问题分析:

这是一类回溯法问题,我们可以考虑采用求组合的方法求解该问题(从1-9这9个数字中选取k个不同的数使它的和为n)


过程相见代码:

class Solution {public:    vector<vector<int>> combinationSum3(int k, int n) {vector<vector<int>> res;vector<int> re;bs(res, re, n, 1, k);return res;}void bs(vector<vector<int>>&res, vector<int>& re,int n,int start,int k){if (!n || !k){if (!n && !k) res.push_back(re);return;}for (int i = start; i <= 9; i++){if (i > n) break;re.emplace_back(i);bs(res, re, n - i, i + 1,k - 1);re.pop_back();}}};