LeetCode | 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 (a1a2, … , 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:
    vector<vector<int> > result;
    vector<int> candidates;
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        this->candidates = candidates;
        sort(this->candidates.begin(),this->candidates.end());
        getCombination(*(new vector<int>()),0,target);
        return result;
    }
    
    void getCombination(vector<int> v, int sum, int target)
    {
        
        int last=INT_MIN;
        if(v.size()>0)
        {
            last = v[v.size()-1];
        }
        int i = 0;
        for(;i<candidates.size();i++)
        {
            if(candidates[i]>=last)
            {
                break;
            }
        }
        for(int j=i;j<candidates.size();j++)
        {
            if(sum + candidates[j]==target)
            {
                v.push_back(candidates[j]);
                result.push_back(v);
                v.pop_back();
            }
            else if(sum + candidates[j]<target)
            {
                v.push_back(candidates[j]);
                getCombination(v, sum+candidates[j],target);
                v.pop_back();
            }
            else
            {
                return;
            }
        }
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/17594497
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞