"One Day together Leetcode" #77. Combinations

Source: Internet
Author: User

One Day together Leetcode

This series of articles has all been uploaded to my github address: Zeecoder ' s GitHub
You are welcome to follow my Sina Weibo, my Sina Weibo blog
Welcome reprint, Reprint please indicate the source

(i) Title

Given-integers n and K, return all possible combinations of k numbers out of 1 ... n.

For example,
If n = 4 and k = 2, a solution is:

[
[2,4],
[3,4],
[2,3],
[+],
[1,3],
[1,4],
]

(ii) Problem solving

The main idea: given two shaping numbers, N and K, find out the combination of all k numbers from the 1~n.

This question is a typical backtracking problem. Analyze the situation when n=4,k=3:

Maintain a vector variable that, when its length is less than 3 o'clock, puts numbers in order.

The first one satisfies a combination of length equal to 3, and then the back pops up 3, and the number 4 continues.

The second satisfies a combination of length equal to 3 as 1,2,4, then pops back 4, no number is released, continues to backtrack 2, then puts 3 and 4

The third satisfies a combination of length equal to 3 for 1,3,4, then pops up 3,4 and 1, putting 2,3,4

The fourth satisfies a combination of length equal to 3 as 2,3,4. At this point, the algorithm ends.

classSolution { Public: vector<vector<int>>Ret vector<vector<int>>CombineintNintK) { vector<int>Temp Dfscombine (N,1, k,temp);returnRet }voidDfscombine (intNintStartintK vector<int>& temp) {if(Temp.size () ==k) {//When the length is k, the result exists in RETRet.push_back (temp);return; } for(inti = start; I <= N; i++) {temp.push_back (i);//Put digitalDfscombine (n,i+1, k,temp); Temp.pop_back ();//Go back to the previous step}    }};

"One Day together Leetcode" #77. Combinations

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.