Leetcode Combination Sum II

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 (a 1 ,  a 2 , ...,  a k ) must is in non-descending order. (Ie, a 1  ≤ a 2  ≤ ... ≤ a k ).
  • The solution set must not contain duplicate combinations.

For example, given candidate set10,1,2,7,6,1,5and target8,
A Solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]

Test instructions: Or the same as the previous one, the number of combinations, but there is one condition is: Each number can only be used once, can not repeat the result set

Idea: A little change on the line, one is every time the subscript is +1, the other is to avoid repetition, skip the same number

Class Solution {public:    void Dfs (vector<int> candidates, int index, int sum, int target, vector<vector<in T>> &res, vector<int> &path) {        if (sum > Target) return;        if (sum = = target) {            res.push_back (path);            return;        }        for (int i = index; i < candidates.size (); i++) {            path.push_back (candidates[i]);            DFS (candidates, i+1, Sum+candidates[i], target, res, path);            Path.pop_back ();            while (I < candidates.size ()-1 && candidates[i] = = candidates[i+1]) i++;        }    }    vector<vector<int> > CombinationSum2 (vector<int> &candidates, int target) {        sort ( Candidates.begin (), Candidates.end ());        vector<vector<int> > Res;        vector<int> path;        DFS (candidates, 0, 0, Target, res, path);        return res;    }};



Leetcode Combination Sum II

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.