40. Combination Sum II LeetCode
2016-03-15 23:34
447 查看
题意:给出一个数组,和target,求所有不重复的这样的组合,从数组从取一些数加和等于target,数组的每个数只能用一次,可能有重复元素。
题解:我先对数组排个序然后dfs,然后为了不产生重复的集合,还是那个技巧,当i是for的后面的元素的时候,如果和之前的重复,那么就跳过这个元素,知道不与之前相同为止,这样就可以使得集合不重复。
题解:我先对数组排个序然后dfs,然后为了不产生重复的集合,还是那个技巧,当i是for的后面的元素的时候,如果和之前的重复,那么就跳过这个元素,知道不与之前相同为止,这样就可以使得集合不重复。
class Solution { public: void dfs(vector<vector<int>>& ans, vector<int>& pre, vector<int>& candidates, int target, int k, int sum) { if(sum == target) ans.push_back(pre); if(sum >= target) return; for(int i = k; i < candidates.size(); i++) { if(i != k && candidates[i] == candidates[i - 1]) continue; pre.push_back(candidates[i]); dfs(ans,pre,candidates,target,i + 1,sum + candidates[i]); pre.pop_back(); } } vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { sort(candidates.begin(),candidates.end()); vector<vector<int>> ans; vector<int> pre; ans.clear(); pre.clear(); dfs(ans,pre,candidates,target,0,0); return ans; } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解