LeetCode 39. Combination Sum

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 39. Combination Sum相关的知识,希望对你有一定的参考价值。

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:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • 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]

 

class Solution {
public:
    void getCombinationSum(int currentSum,vector<int>& candidates, int index,vector <vector<int>> &solution, vector <int> &result, int target){
        if(currentSum == target){ //如果和等于目标,则把该结果压入solution,返回上一          层
            solution.push_back(result);
            return;
        }
        else{  //如果和小于目标,则可以继续加入值
            for(int i = index; i < candidates.size() ;i++){
                currentSum += candidates[i];
                if(currentSum> target){//加值后大于目标,则该队列不可能再复合要求,直接break该循环
                  currentSum -= candidates[i];
                  break;
                }
                result.push_back(candidates[i]);//把当前结果压入,继续递归调用
                getCombinationSum(currentSum,candidates,i,solution,result,target);
                currentSum -= candidates[i];//返回的情况说明之前找到了一个解,所以把最后压入的去掉,然后继续循环添加新值
                result.pop_back();
            }
        }
        
        
    }

   
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector <vector<int>> solution;
        vector <int> result;
        int currentSum = 0;
        sort(candidates.begin(),candidates.end());//先把输入排序,确保输出是有序的
        getCombinationSum(currentSum,candidates,0,solution,result,target);
        return solution;
    }
};

 

以上是关于LeetCode 39. Combination Sum的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode题意分析&解答39. Combination Sum

Leetcode 39. Combination Sum

[leetcode-39-Combination Sum]

leetcode 39. Combination Sum

[array] leetcode - 39. Combination Sum - Medium

LeetCode39Combination Sum