My c++ solution


  • 0
    B
    class Solution {
    public:
        vector<vector<int>> combinationSum3(int k, int n) {
        	vector<vector<int>> res;
        	vector<int> cur;
        	int num = 1;
        	int sum = 0;
        	while (true)
        	{
        		int size = cur.size();
        		if (size == k && sum == n)
        		{
        			res.push_back(cur);
        		}
        		if (size == k || num > 9 ||sum + (k - size)*num > n)
        		{
        			if (cur.empty())
        				return res;
        			num = cur.back();
        			cur.pop_back();
        			sum -= num;
        			num++;
        		}
        		else
        		{
        			cur.push_back(num);
        			sum += num;
        			num++;
        		}
        	}
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.