216. Combination Sum III(Leetcode每日一题-2020.09.11)

Problem

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.

Note:

  • All numbers will be positive integers.
  • The solution set must not contain duplicate combinations.

Example1

Input: k = 3, n = 7
Output: [[1,2,4]]

Example2

Input: k = 3, n = 9
Output: [[1,2,6], [1,3,5], [2,3,4]]

Solution

class Solution {
     
public:
    vector<vector<int>> ret;
    int _n;
    int _k;
    vector<vector<int>> combinationSum3(int k, int n) {
     

        _k = k;
        _n = n;
        vector<int> comb;
        int sum = 0;
        
        dfs(1,sum,comb);

        return ret;
    }

    void dfs(int start,int &sum,vector<int> &comb)
    {
     
        if(sum > _n || comb.size() > _k)
            return;

        if(sum == _n && comb.size() == _k)
        {
     
            ret.push_back(comb);
            return;
        }

       
        for(int i = start;i<=9;++i)
        {
     
            comb.push_back(i);
            sum += i;
            dfs(i+1,sum,comb); 
            sum -= i;
            comb.pop_back();
        }
        
    }
};

你可能感兴趣的:(leetcode回溯)