LeetCode Combination Sum

来源:互联网 发布:太平公主知乎 编辑:程序博客网 时间:2024/06/05 22:46

题目:

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) {cs = 0;res.clear();sort(candidates.begin(), candidates.end());dfs(0, candidates.size(), candidates, target);return res;}private:int a[1000];int cs;vector<vector<int> > res;void dfs(int dep, int maxDep, vector<int> &candidates, int &target) {if (cs > target)return;if (cs == target) {if (cs == target) {vector<int> ans;for (int i = 0; i < dep; i++) {for (int j = 0; j < a[i]; j++)ans.push_back(candidates[i]);}res.push_back(ans);}return;}if (dep == maxDep)return;for (int i = 0; i <= target / candidates[dep]; i++) {a[dep] = i;cs += candidates[dep] * i;dfs(dep + 1, maxDep, candidates, target);cs -= candidates[dep] * i;a[dep] = 0;}}};



0 0
原创粉丝点击