[LeetCode] Combination Sum II
2012-10-29 17:36
393 查看
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
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
A solution set is:
类似与之前的Combination Sum的DFS,有一点需要注意,如何避免重复。如果两个数相同,我们先用前一个数,只有当前一个数用了,这个数才能使用。
例如:1 1。
当我们要使用第二个1时,我们要检查他的前面一个1是否使用了,当未被使用时第二个1就不能使用。
Each number in C may only be used once in the combination.
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
10,1,2,7,6,1,5and target
8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
类似与之前的Combination Sum的DFS,有一点需要注意,如何避免重复。如果两个数相同,我们先用前一个数,只有当前一个数用了,这个数才能使用。
例如:1 1。
当我们要使用第二个1时,我们要检查他的前面一个1是否使用了,当未被使用时第二个1就不能使用。
class Solution { private: vector<vector<int> > ret; vector<int> a; public: void solve(int dep, int maxDep, vector<int> &num, int target) { if (target < 0) return; if (dep == maxDep) { if (target == 0) { vector<int> res; for(int i = 0; i < maxDep; i++) for(int j = 0; j < a[i]; j++) res.push_back(num[i]); ret.push_back(res); } return; } for(int i = 0; i <= min(target / num[dep], 1); i++) { a[dep] = i; if (i == 1 && dep > 0 && num[dep-1] == num[dep] && a[dep-1] == 0) continue; solve(dep + 1, maxDep, num, target - i * num[dep]); } } vector<vector<int> > combinationSum2(vector<int> &num, int target) { // Start typing your C/C++ solution below // DO NOT write int main() function sort(num.begin(), num.end()); a.resize(num.size()); ret.clear(); if (num.size() == 0) return ret; solve(0, num.size(), num, target); return ret; } };
相关文章推荐
- Java for LeetCode 040 Combination Sum II
- leetcode: Combination Sum II
- [Leetcode]Combination Sum II
- LeetCode40 Combination Sum II
- [Leetcode] Combination Sum II
- [LeetCode39]Combination Sum 和[LeetCode40]Combination Sum II
- LeetCode40 Combination Sum II 解析
- LeetCode Online Judge 题目C# 练习 - Combination Sum II
- Combination Sum II 组合数求和之2-Leetcode
- 《leetCode》:Combination Sum II
- leetcode 40: Combination Sum II
- [LeetCode]Combination Sum II
- [Leetcode]_40 Combination Sum II
- [Leetcode] Combination Sum II (Java)
- [LeetCode] Combination Sum II
- leetcode 40-Combination Sum II
- leetcode之Combination Sum && Combination Sum II
- leetcode-combination sum and combination sum II
- 39 leetcode - Combination Sum II
- 【LeetCode】Combination Sum II