Typical recursion usage.
class Solution { vector<vector<int>> ret; void dfs(vector<int> curr, int currSum, int maxN, int n, int k) { // Ending if (currSum == n) { if (curr.size() == k) { std::reverse(curr.begin(), curr.end()); ret.push_back(curr); } return; } int rest = n - currSum; for (int c = maxN; c >= 1; c--) { if (c <= rest) { vector<int> ncurr = curr; ncurr.push_back(c); dfs(ncurr, currSum + c, c - 1, n, k); } } } public: vector<vector<int>> combinationSum3(int k, int n) { dfs(vector<int>(), 0, 9, n, k); return ret; } };