码迷,mamicode.com
首页 > 其他好文 > 详细

Combination Sum II

时间:2014-09-02 00:07:23      阅读:258      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   os   io   使用   strong   ar   

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, a1a2 ≤ … ≤ 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]

思路:先对输入数据进行排序,然后使用DFS即可。因为每个元素只出现一次,为了避免重复,递归调用应从下一个比当前元素大的元素开始。

 1 class Solution {
 2 public:
 3     vector<vector<int> > combinationSum2( vector<int> &num, int target ) {
 4         vector<int> combination;
 5         sort( num.begin(), num.end() );
 6         vector<int>::iterator begin = num.begin(), end = num.end();
 7         CombinationSub( combination, begin, end, target );
 8         return combinations;
 9     }
10 private:
11     void CombinationSub( vector<int> combination, vector<int>::iterator &begin, vector<int>::iterator &end, int target ) {
12         if( begin == end || target < *begin ) { return; }
13         vector<int>::iterator next = upper_bound( begin, end, *begin );
14         CombinationSub( combination, next, end, target );
15         for( int i = 0; begin+i != next && target >= *begin; ++i ) {
16             target -= *begin;
17             combination.push_back( *begin );
18             if( target == 0 ) { combinations.push_back( combination ); break; }
19             CombinationSub( combination, next, end, target );
20         }
21         return;
22     }
23     vector<vector<int>> combinations;
24 };

 

Combination Sum II

标签:des   style   blog   color   os   io   使用   strong   ar   

原文地址:http://www.cnblogs.com/moderate-fish/p/3950102.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!