LeetCode--Combination Sum(DFS)
2015-03-18 18:20
357 查看
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]
代码如下:
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]
代码如下:
class Solution { public: int comb(vector<int> & candidates,int sum,int target,int index,vector<vector<int> >& ans,vector<int> &tmp) { if(sum == target) { ans.push_back(tmp); return 0; } if(sum > target) return 0; for(int i = index;i < candidates.size();i++) { if(i > index&&candidates[i] == candidates[i-1]) //因为同一个index的数可以被重复使用,相同值的元素则不必在使用 continue; tmp.push_back(candidates[i]); comb(candidates,sum+candidates[i],target,i,ans,tmp); tmp.pop_back(); } return 0; } vector<vector<int> > combinationSum(vector<int> &candidates, int target) { vector<vector<int> >ans; vector<int> tmp; tmp.clear(); ans.clear(); sort(candidates.begin(),candidates.end()); comb(candidates,0,target,0,ans,tmp); return ans; } };
相关文章推荐
- LeetCode-39-Combination Sum, 回溯dfs,Python的list.append()覆盖前面,tuple,set
- LeetCode-39-Combination Sum(DFS)-Medium
- Combination Sum 系列问题(leetcode dfs回溯,动归)由浅入深DFS
- leetcode 日经贴,Cpp code -Combination Sum
- LeetCode-Surrounded Regions-BFS/DFS
- leetcode--Combination Sum
- Leetcode:Subsets 求数组的所有子集(DFS)
- 126. Word Ladder II 、 127. Word Ladder(leetcode BFS+DFS)
- leetcode dfs Subsets II
- 2017.10.29 LeetCode - 113. Path Sum II【DFS的运用】【补】
- 利用bds和dfs解决 LeetCode 107. Binary Tree Level Order Traversal II
- LEETCODE: Combination Sum
- leetcode 144. Binary Tree Preorder Traversal 二叉树前序遍历 + 深度优先遍历DFS
- [leetcode][tree][dfs] Populating Next Right Pointers in Each Node
- leetcode--Combination Sum
- leetcode -- Generate Parentheses -- DFS题目重点
- leetCode解题报告之Palindrome Partitioning I,II(DFS,DP)
- [leetcode][dfs] Lowest Common Ancestor of a Binary Search Tree
- leetCode解题报告之Palindrome Partitioning I,II(DFS,DP)
- LeetCode | Combination Sum(元素的和)