LeetCode:Combination Sum
2017-09-05 11:19
330 查看
Given a set of candidate numbers (C) (without duplicates) 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.
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]
]
思路:
这个问题我看到就想到了找余下的值,也就是7-2=5,则找5在不在数组,不在就把2推进数组,然后5-2=3,找3,在的话就把3推进数组,然后就把这个小数组加入到大数组里,不过目前代码存在的问题是并不能找出所有解,只能找出部分,正在解决中orz。。。
目前出现的问题:
The same repeated number may be chosen from C unlimited number of times.
Note:
All numbers (including target) will be positive integers.
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]
]
思路:
这个问题我看到就想到了找余下的值,也就是7-2=5,则找5在不在数组,不在就把2推进数组,然后5-2=3,找3,在的话就把3推进数组,然后就把这个小数组加入到大数组里,不过目前代码存在的问题是并不能找出所有解,只能找出部分,正在解决中orz。。。
目前出现的问题:
代码如下: class Solution { public: vector<vector<int>> combinationSum(vector<int>& candidates, int target) { vector<vector<int>>res; int flag = 0; //bool is_add=false; //int count=candidates.size(); for (int i = 0; i<candidates.size(); i++) { int temp = target; vector<int>m_vec; m_vec.push_back(candidates[i]); while (temp>0) { if(target%candidates[i]==0&&target!=candidates[i]) { int count=target/candidates[i]; while(count!=1) { m_vec.push_back(candidates[i]); count--; } res.push_back(m_vec); break; } temp = temp - candidates[i]; if (bfind(candidates, temp)) { m_vec.push_back(temp); temp = 0; res.push_back(m_vec); break; } if (temp == 0) { res.push_back(m_vec); break; } m_vec.push_back(candidates[i]); } //j++; } return res; } bool bfind(vector<int>& candidates, int target)//二分查找 { vector<int>test(candidates); sort(test.begin(), test.end()); int div = (test.size()-1) / 2; while (test[div] != target) { if (test[div]>target) div = (div-1)/2; else div = (test.size() + div ) / 2 ; if (test[div] == target) return true; else if (div == 0 && test[div] != target) return false; else if (div == test.size() - 1 && test[div] != target) return false; } return true; } };
相关文章推荐
- [leetcode 39] Combination Sum
- Combination Sum(leetcode)
- Leetcode: Combination Sum
- 【LeetCode】Combination Sum
- LeetCode_Combination Sum
- [Leetcode] Combination Sum
- [Leetcode] Combination Sum (Java)
- Leetcode - Combination Sum
- LeetCode 39 Combination Sum
- [leetcode]Combination Sum
- LeetCode--Combination Sum
- Java for LeetCode 039 Combination Sum
- LeetCode——Combination Sum
- Combination Sum--LeetCode
- [leetcode]Combination Sum
- [LeetCode]Combination Sum
- [LeetCode]Combination Sum
- [LeetCode] 017: Combination Sum
- [LeetCode] Combination Sum
- LeetCode(39) Combination Sum