Combination Sum II - LeetCode

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 10,1,2,7,6,1,5 and target 8
A solution set is: 
[1, 7] 
[1, 2, 5] 
[2, 6] 
[1, 1, 6] 

 

思路:和Combination Sum这道题基本思想是相同的。需要注意的不同点主要有两个:一个是因为每个数只能用一次,因此在枚举完后继续递归时要从下一位开始枚举,而不再是当前位置;另一个还是因为每个数只能用一次,因此要注意原数组中可能有重复数字的情况,因此这里在枚举过程中如果遇见了相同的数,则只枚举一次,然后跳过剩下的重复数字。

 1 class Solution {
 2 public:
 3     void assist(vector<int>& candidates, vector<vector<int> >& res, vector<int>& cur, int target, int st)
 4     {
 5         if (target == 0)
 6         {
 7             res.push_back(cur);
 8             return;
 9         }
10         if (st == candidates.size()) return;
11         for (int i = st, n = candidates.size(); i < n && candidates[i] <= target; i++)
12         {
13             cur.push_back(candidates[i]);
14             assist(candidates, res, cur, target - candidates[i], i + 1);
15             cur.pop_back();
16             while (i < n && candidates[i] == candidates[i + 1])
17                 i++;
18         }
19     }
20     vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
21         vector<vector<int> > res;
22         vector<int> cur;
23         sort(candidates.begin(), candidates.end(), less<int>());
24         assist(candidates, res, cur, target, 0);
25         return res;
26     }
27 };

 

posted @ 2015-11-10 14:28  fenshen371  阅读(141)  评论(0编辑  收藏  举报