跳转至

216. Combination Sum III

Leetcode Array Backtracking

题目

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.

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]]

分析

这道题和前面的Combination Sum主要的区别是它规定了有k个数。所以除了base case变动以外,其他都可以保持一致。

class Solution {
public:
    void combinationSum3Helper(int k, int n, vector<int>& candidates, vector<vector<int>>& res, vector<int>& chosen, int position){

        if (k==0){
            //base case
            if (n==0){
                res.push_back(chosen);
            }
        }else{
            for (int i=position; i<candidates.size(); i++){
                // choose
                chosen.push_back(candidates[i]);

                // explore
                combinationSum3Helper(k-1, n-candidates[i], candidates, res, chosen, i+1);

                // unchoose
                chosen.pop_back();
            }
        }


    }

    //Find all possible combinations of k numbers that add up to a number n
    vector<vector<int>> combinationSum3(int k, int n) {
        vector<int> candidates={1,2,3,4,5,6,7,8,9}, chosen;
        vector<vector<int>> res;
        combinationSum3Helper(k, n, candidates, res, chosen, 0);
        return res;

    }
};