LC 216. Combination Sum III

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

Runtime: 0 ms, faster than 100.00% of C++ online submissions for Combination Sum III.

class Solution {
public:
  vector<vector<int>> combinationSum3(int k, int n) {
    vector<vector<int>> ret;
    vector<int> path;
    int target = 0;
    helper(k, n, 0, 0, target, path, ret);
    return ret;
  }
  void helper(const int k ,const int n, int i_th, int prev, int& target, vector<int>& path, vector<vector<int>>& ret){
    if(i_th == k && n == target) {
      ret.push_back(path);
      return ;
    }
    for(int i=prev+1; i < 10; i++){
      path.push_back(i);
      target += i;
      helper(k, n, i_th+1, i, target, path, ret);
      target -= i;
      path.pop_back();
    }
  }
};
原文地址:https://www.cnblogs.com/ethanhong/p/10208048.html