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 = 7
Output:
[[1,2,4]]
Example 2:
Input: k = 3, n = 9
Output:
[[1,2,6], [1,3,5], [2,3,4]]
方法:递归调用即可
class Solution { private: void recursive(int sum,vector<int>& combination,vector<vector<int>>& res,int now,int target,int layer,int k){ if(sum==target&&layer==k){ res.push_back(combination); return; } for(int i=now+1;i<=9;i++){ if(layer+1>k) return; combination.push_back(i); recursive(sum+i,combination,res,i,target,layer+1,k); combination.pop_back(); } } public: vector<vector<int>> combinationSum3(int k, int n) { vector<vector<int>> res; vector<int> combination; recursive(0,combination,res,0,n,0,k); return res; } };转载于:https://www.cnblogs.com/GoFly/p/5751053.html
相关资源:JAVA上百实例源码以及开源项目