[Leetcode] Combination Sum II combination

Source: Internet
Author: User

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 is used once in the combination.

Note:

    • All numbers (including target) would be positive integers.
    • Elements in a combination (a1, a 2, ..., aK) must is in non-descending order. (ie, a1≤ a2≤ ... ≤ ak).
    • The solution set must not contain duplicate combinations.

For example, given candidate set and 10,1,2,7,6,1,5 target 8 ,
A Solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]

This problem with the previous combination Sum combination of the essence of no difference, only need to change a little bit, before the question given the array of numbers can be reused, and this problem can not be reused, just need to modify two places on the basis of the previous, first in the recursive for loop plus if (i > Start && num[i] = = Num[i-1]) continue; This prevents duplicates from appearing in the res, and then replaces the parameters in the recursive call Combinationsum2dfs with i+1, so that the numbers in the array are not reused, and the code is as follows:

classSolution { Public: Vector<vector<int> > CombinationSum2 (vector<int> &num,inttarget) {Vector<vector<int> >Res; Vector<int> out;        Sort (Num.begin (), Num.end ()); Combinationsum2dfs (num, Target,0, out, RES); returnRes; }    voidCombinationsum2dfs (vector<int> &num,intTargetintStart, vector<int> & out, vector<vector<int> > &Res) {        if(Target <0)return; Else if(target = =0) Res.push_back ( out); Else {             for(inti = start; I < num.size (); ++i) {if(i > Start && num[i] = = Num[i-1])Continue;  out. Push_back (Num[i]); Combinationsum2dfs (num, Target-Num[i], i +1, out, RES);  out. Pop_back (); }        }    }};

[Leetcode] Combination Sum II combination

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.