niuworld/LeetCodeSolution

39.Combination Sum

Opened this issue · 0 comments

Question:

Given a set of candidate numbers (C) and a target number (T), find >all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of >times.

Note:

  1. All numbers (including target) will be positive integers.
  2. Elements in a combination (a1, a2, … , ak) must be in non-descending >order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  3. The solution set must not contain duplicate combinations.

For example, given candidate set 2,3,6,7 and target 7,

A solution set is:

[7]

[2, 2, 3]

Solution:

backtracking

class Solution {
public:
        vector<int>res;
        vector<vector<int>>finalres;

 void helper(vector<int> & ca, int tar ,vector<int>&re ,vector<vector<int>>&final ,int begin){
        if ( tar == 0){
            final.push_back(re);
            return;
        }
        for( int i = begin; i <= ca.size() - 1 && ca[i] <= tar; ++i){
             re.push_back(ca[i]);
            helper(ca, tar - ca[i], re , final, i);
             re.pop_back();
        }
    }

 vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
       sort(candidates.begin(), candidates.end());
         helper(candidates, target , res , finalres , 0);
         return finalres;
    }
};