Combination Sum II [LeetCode]

Problem description: http://oj.leetcode.com/problems/combination-sum-ii/

Basic idea: use recursive approach, remember to avoid duplicate item.

 1 class Solution {

 2 public:

 3     bool isExist(vector<vector<int> > &combinations, vector<int> &item) {

 4         for(auto com: combinations){

 5             if(com.size() == item.size()){

 6                 int k;

 7                 for(k = 0; k < com.size(); k++){

 8                     if(com[k] != item[k])

 9                         break;

10                 }

11                 if(k == com.size())

12                     return true;

13             }

14         }  

15         return false;

16     }

17     vector<vector<int> > combinationSum2(vector<int> &num, int target) {

18         // Note: The Solution object is instantiated only once and is reused by each test case.

19         vector<vector<int> >  combinations;

20         std::sort(num.begin(), num.end());

21         int is_target_equal_to_num = 0;

22         for(int i = 0; i < num.size(); i ++){

23             if(num[i] == target && !is_target_equal_to_num){

24                 is_target_equal_to_num = 1;

25                 vector<int> combination(1, target);

26                 combinations.push_back(combination);

27             }else if(num[i] > target) {

28                 break;

29             }else {
32 vector<int> sub_num(num.begin() + i + 1, num.end()); 33 vector<vector<int> > sub_combinations = combinationSum2(sub_num, target - num[i]); 34 for (auto item : sub_combinations) { 35 item.insert(item.begin(), num[i]); 36 if(!isExist(combinations, item)) 37 combinations.push_back(item); 38 } 39 } 40 } 41 42 return combinations; 43 } 44 };

 

你可能感兴趣的:(LeetCode)