Combination Sum

来源:互联网 发布:网络平台招商话术 编辑:程序博客网 时间:2024/05/01 00:24

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> > combinationSum(vector<int> &candidates, int target) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        vector< vector <vector<int> > > sum(target+1);        int n = candidates.size();        for(int i = 1; i <= target; ++i){            for(int j = 0; j < n; ++j){                if(i < candidates[j]){                    continue;                }                else if(i == candidates[j]){                    sum[i].push_back(vector<int>());                    sum[i].back().push_back(candidates[j]);                }                else{                    int tmp = i - candidates[j];                    for(int k = 0; k < sum[tmp].size(); ++k){                        if(sum[tmp][k].back() <= candidates[j]){                            sum[i].push_back(vector<int>(sum[tmp][k]));                            sum[i].back().push_back(candidates[j]);                        }                    }                }            }        }        return sum[target];    }};


原创粉丝点击