Leetcode 216. Combination Sum III (Medium) (cpp)

来源:互联网 发布:如何测试网络 编辑:程序博客网 时间:2024/05/16 07:35

Leetcode 216. Combination Sum III (Medium) (cpp)

Tag: Array, Backtracking

Difficulty: Medium


/*216. Combination Sum III (Medium)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.Example 1:Input: k = 3, n = 7Output:[[1,2,4]]Example 2:Input: k = 3, n = 9Output:[[1,2,6], [1,3,5], [2,3,4]]*/class Solution {public:vector<vector<int>> combinationSum3(int k, int n) {vector<vector<int>> res;vector<int> res_sub;combinationSum3(k, n, 1, res, res_sub);return res;}private:void combinationSum3(int k, int n, int start, vector<vector<int>>& res, vector<int>& res_sub) {if (n == 0 && res_sub.size() == k) {res.push_back(res_sub);return;}for (int i = start; i < 10 && i <= n && res_sub.size() < k; i++) {res_sub.push_back(i);combinationSum3(k, n - i, i + 1, res, res_sub);res_sub.pop_back();}}};


0 0