Leetcode -- Combination sum II

Source: Internet
Author: User

Idea: similar to the previous question, but an index array is added to record the stored element index in the result,

Used to determine whether the current element is the same as the previous one and whether the previous one has been used.

It is mainly used to solve the problem of repeated solutions.

 1 class Solution { 2 public: 3     vector<vector<int> >ans; 4     vector<vector<int> > combinationSum2(vector<int> &num, int target) { 5         if(num.size() == 0) 6             return ans; 7         sort(num.begin(),num.end()); 8         vector<int> res; 9         vector<int> index;10         calSum(num,target,0,res,index);11         return ans;12     }13     void calSum(vector<int> &num,int target,int s,vector<int> &res,vector<int> &index)14     {15         if(target < 0)16             return;17         if(target == 0)18         {19             ans.push_back(res);20             return;21         }22         int i;23         for(i = s ; i < num.size() ; ++i)24         {25             if(i >0 && index[index.size()-1] != i-1 && num[i] == num[i-1])26                 continue;27             index.push_back(i);28             res.push_back(num[i]);29             calSum(num,target-num[i],i+1,res,index);30             res.pop_back();31             index.pop_back();32         }33         return;34     }35 };

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.