Subset series (2) subsets meeting specific requirements, for example, [leetcode] combination, combination sum I, II

Source: Internet
Author: User
Introduction

After the previous subset series (1), we will discuss the subset solution method with additional conditions.

This type of question is also a subset, but not all of them are returned, and it is often a subset that meets certain requirements.

The idea of solving this type of question can be slightly improved in the previous article.

 

Example 1: Evaluate all subsets with a fixed number of elements

Combinations

Given two integersNAndK, Return all possible combinationsKNumbers out of 1...N.

For example,
IfN= 4 andK= 2, a solution is:

[  [2,4],  [3,4],  [2,3],  [1,2],  [1,3],  [1,4],]
class Solution {public:    vector<vector<int> > combine(int n, int k) {    }}

 

Thought 1:In essence, this question is to find all the subsets of K in the set [1, 2,... n.

Using the idea in the previous article: Each element has two possibilities in the subset: appearance or not. We only need to judge both cases to see whether the current subset meets the requirements. In this question, the requirements to be met are: size = K

class Solution {public:    vector<vector<int> > combine(int n, int k) {        if(n < k) return res;        combineCore(1, n, k);        return res;    }private:    vector<int> path;    vector<vector<int> > res;    void combineCore(int st, int n, int k){        if(path.size() == k){             res.push_back(path);            return;        }        if(st > n) return;        combineCore(st+1, n, k); //case1: skip        path.push_back(st);        combineCore(st+1, n, k); //case2: not skip        path.pop_back();    }};

 

AC 52 Ms.

Idea 2:Of course, we can also do this with Backtracking: when selecting the first number of subsets, we can go to [1, 2 ,..., n-(k-1)] So many in the selection, after selecting the first number, assuming that the selected is Q, then the second number of the subset can only from [q + 1, q + 2 ,...., n-(K-2)] these numbers are selected.

Therefore, in a recursive function, each time a recursion is performed, K is reduced by 1, indicating that the number to be determined in the subset is fewer and fewer. At the same time, a parameter is required to indicate the starting element of the optional range, assume it is St.

Code:

class Solution {public:    vector<vector<int> > combine(int n, int k) {        if(n < k) return res;        vector<int> v;        combineCore(1, n, k, v);        return res;    }private:    vector<vector<int> > res;    void combineCore(int st, int n, int k, vector<int> &v){        if(k == 0){             res.push_back(v);            return;        }        for(int i = st; i <= n-k+1; ++i){            v.push_back(i);            combineCore(i+1, n, k-1, v);            v.pop_back();        }    }};

AC 48 Ms.

 

Example 2.1: Evaluate all subsets of an element and a specified value

Combination sum

Given a set of candidate numbers (C) And a target number (T), Find all unique combinations inCWhere the candidate numbers sumsT.

TheSameRepeated number may be chosen fromCUnlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (A1,A2 ,... ,AK) must be in Non-descending order. (ie,A1 ≤A2 ≤... ≤AK ).
  • The solution set must not contain duplicate combinations.

 

For example, given candidate set2,3,6,7And target7,
A solution set is:
[7] 
[2, 2, 3] 

class Solution {public:    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {    }};

 

Idea: Start With the appearance or absence of each element. Note: an element may not be used or used for multiple times.

We can sort candidates first and then deduplicate it. On the basis of such candidates, we do not need to move one digit behind after considering the "occurrence.

Class solution {public: vector <int> combinationsum (vector <int> & candidates, int target) {If (target <= 0) return res; If (candidates. size () = 0) return res; sort (candidates. begin (), candidates. end (); // sort if (candidates. size ()> 1) {// deduplicated int p = 0, q = 1; while (q <candidates. size () {If (candidates [p]! = Candidates [Q]) {candidates [++ p] = candidates [q ++];} else {++ Q ;}} candidates. erase (candidates. begin () + p + 1, candidates. end ();} combinsumcore (candidates, 0, target); Return res;} PRIVATE: vector <int> path; vector <int> res; void combinsumcore (vector <int> & candidates, int St, int target) {If (target = 0) {res. push_back (PATH); return;} If (target <0 | st> = candidates. size () | candidat Es [st]> Target) return; combinsumcore (candidates, ST + 1, target); // case1: Skip path. push_back (candidates [st]); combinsumcore (candidates, St, target-candidates [st]); // case2: not skip, but not 1 in St, because the number can be used multiple times. Path. pop_back ();}};

 

AC 60 ms

 

Example 2.2: Evaluate all subsets of an element and a specified value

Unlike example 2.1, an element can only be used once.

Combination sum II

Given a collection of candidate numbers (C) And a target number (T), Find all unique combinations inCWhere the candidate numbers sumsT.

Each number inCMay only be usedOnceIn 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,A1 ≤A2 ≤... ≤AK ).
  • 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] 

class Solution {public:    vector<vector<int> > combinationSum2(vector<int> &num, int target) {}};

 

Idea: num in the question contains repeated elements, each element can only be used once.

We still sort num first, so the repeated elements must be together. These repeated elements are proposed separately, because for such elements, its "appearance or absence" issue is not only related to the overall condition (here the overall condition is the sum of targets), but also to its adjacent elements.

Taking [, 3] as an example, we propose [, 2] separately. The combination of this part can only be: [], [2], [2, 2], [2, 2].

Class solution {public: vector <int> combinationsum2 (vector <int> & num, int target) {If (Num. size () = 0) return res; sort (Num. begin (), num. end (); combinationsumcore (Num, 0, target); Return res;} PRIVATE: vector <int> path; vector <int> res; void combinationsumcore (vector <int> & num, int start, int target) {If (target <0) return; If (target = 0) {vector <int> V; res. push_back (PATH); R Eturn;} If (start <num. size () {int I = start + 1; for (; I <num. size () & num [start] = num [I]; ++ I); combinationsumcore (Num, I, target); // case1: jump out the same int sum = 0, j = I-1; For (; j> = start; -- j) {sum + = num [J]; Path. push_back (Num [J]); combinationsumcore (Num, I, target-sum); // case2: All usage conditions in the same segment.} For (j = I-1; j >=start; -- j) {path. pop_back ();}}}};

 

AC 96 Ms

 

Conclusion

There are many problems that can be converted into a subset, but the subset must meet certain conditions.

To solve this problem, we can use recursion to implement the "appearance or absence" of each element.

Subset series (2) subsets meeting specific requirements, for example, [leetcode] combination, combination sum I, 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.