Combination Sum III Solutions in C++
Number 216
Difficulty Medium
Acceptance 56.7%
Link LeetCode
Other languages Go
Solutions
C++ solution by haoel/leetcode
// Source : https://leetcode.com/problems/combination-sum-iii/// Author : Hao Chen// Date : 2015-06-11#include <stdlib.h>#include <iostream>#include <vector>using namespace std;void combinationSumHelper(vector<int>& candidates, int start, int num, int target,vector<int>& solution, vector< vector<int> >& results) {if (target < 0|| solution.size() > num){return;}if (target == 0 && solution.size()==num){results.push_back(solution);return;}for (int i=start; i<candidates.size(); i++){solution.push_back(candidates[i]);combinationSumHelper(candidates, i+1, num, target-candidates[i], solution, results);solution.pop_back();}}vector< vector<int> > combinationSum3(int k, int n) {vector<int> v;for (int i=1; i<=9; i++){v.push_back(i);}vector< vector<int> > result;vector<int> solution;combinationSumHelper(v, 0, k, n, solution, result);return result;}void PrintResults(int k, int n, vector< vector<int> >& results) {cout << "k=" << k << ", n=" << n << "\t";for (int i=0; i<results.size(); i++){cout << "[";for (int j=0; j<results[i].size(); j++){cout << results[i][j] << (j!=results[i].size()-1 ? ",":"]") ;}cout << ( i!=results.size()-1 ? ", " : "" );}cout << endl;}int main(int argc, char** argv){int k = 3, n =9;if (argc > 2){k = atoi(argv[1]);n = atoi(argv[2]);}vector< vector<int> > results;results = combinationSum3(k, n);PrintResults(k,n, results);return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/combination-sum-iii/description//// Author : liuyubobobo/// Time : 2018-03-04#include <iostream>#include <vector>using namespace std;class Solution {public:vector<vector<int>> combinationSum3(int k, int n) {vector<vector<int>> res;vector<int> cur_res;solve(1, k, n, cur_res, res);return res;}private:void solve(int index, int k, int n,vector<int>& cur_res, vector<vector<int>>& res){if(n == 0 && k == 0){res.push_back(cur_res);return;}if(k == 0)return;for(int i = index ; i <= 9 ; i ++)if(n >= i){cur_res.push_back(i);solve(i + 1, k - 1, n - i, cur_res, res);cur_res.pop_back();}return;}};void print_vec(const vector<int>& vec){for(int e: vec)cout << e << " ";cout << endl;}int main() {vector<vector<int>> res1 = Solution().combinationSum3(3, 7);for(const vector<int>& a_res: res1)print_vec(a_res);cout << endl;vector<vector<int>> res2 = Solution().combinationSum3(3, 9);for(const vector<int>& a_res: res2)print_vec(a_res);return 0;}