[leetcode]Combination Sum
2014-06-17 19:25
399 查看
Combination Sum
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C wherethe 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,7and
target
7,
A solution set is:
[7]
[2, 2, 3]
解题思路:先将原集合排序,然后将原集合中小于等于目标的元素拷贝出来。一定程度上减小了递归的分支。
最后用递归的思想去查找哪些元素之合为给定的目标数。
class Solution { public: //t目标数组 i当前下标 sum当前选中元素之和 vi暂存元素容器 vvi目标存储位置 void innerCS(vector<int> &t, int i, int sum, int target, vector<int> &vi, vector<vector<int> > &vvi){ int n = t.size(); if(sum > target || i == n) return; //剪支 if(sum == target) { vvi.push_back(vi); return; } for(int j = i; j < n; j++){ vi.push_back(t[j]); innerCS(t, j, sum + t[j], target, vi, vvi); vi.pop_back(); } } vector<vector<int> > combinationSum(vector<int> &candidates, int target) { vector<vector<int> > vvi; int n = candidates.size(); if(n == 0) return vvi; sort(candidates.begin(), candidates.end()); vector<int> t; for(int i = 0; i < n; i++){ if(candidates[i] > target) break; t.push_back(candidates[i]); //一定情况下的剪支 } vector<int> vi; innerCS(t, 0, 0, target, vi, vvi); return vvi; } };
相关文章推荐
- [Leetcode] Combination Sum
- leetcode--Combination Sum
- [LeetCode]039-Combination Sum
- LeetCode_39---Combination Sum
- LeetCode : Combination Sum [java]
- [LeetCode] Combination Sum
- leetcode【39+40+216+377 Combination Sum 相关】【python】
- LeetCode-Combination Sum-组合加和-回溯
- [leetcode刷题系列]Combination Sum
- leetcode 刷题之路 23 Combination Sum
- Java [Leetcode 39]Combination Sum
- [leetcode] Combination Sum
- Combination Sum - LeetCode
- LeetCode039 Combination Sum
- LeetCode-Combination Sum
- [leetcode] Combination Sum
- LeetCode: Combination Sum
- leetcode-Combination Sum
- leetcode之Combination Sum
- LeetCode39 - Combination Sum