[LeetCode]Combination Sum
Posted skycore
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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 (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]
解题思路:
回溯法,具体如下:
对于[2, 3, 6, 7], target = 7:
1. 第一个数字选择2,target = 7 -2 = 5;
2. 第二个数字继续选择2(可以重复),target = 5 - 2 = 3;
3. 第三个数字继续选择2, target = 1;
4. 没有元素比target小,回退到第三步,target = 3;
5. 第三个数字选择3,target = 0.
1 class Solution { 2 public: 3 vector<vector<int>> combinationSum(vector<int>& candidates, int target) { 4 sort(candidates.begin(), candidates.end()); 5 vector<vector<int>> result; 6 vector<int> elem; 7 combinationSum(candidates, 0, target, result, elem); 8 return result; 9 } 10 private: 11 void combinationSum(vector<int> &candidates, int index, int target, vector<vector<int>> &result, vector<int> &elem) { 12 if (target == 0) { 13 result.push_back(elem); 14 return; 15 } 16 17 for (int i = index; i < candidates.size() && candidates[i] <= target; ++i) { 18 if (i == 0 || candidates[i] != candidates[i -1]) { 19 elem.push_back(candidates[i]); 20 combinationSum(candidates, i, target - candidates[i], result, elem); 21 elem.pop_back(); 22 } 23 } 24 } 25 };
以上是关于[LeetCode]Combination Sum的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode OJ 39. Combination Sum
LeetCode 216. Combination Sum III