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