Leetcode series [4] ---- combinations
Code cowboy
Question:
Given two integersNAndK, Return all possible combinationsKNumbers out of 1...N.
Test example:
IfN= 4 andK= 2, a solution is:
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4],]
Analysis:
This topic provides two integers, so that K numbers can be selected from 1-N and all combination methods can be provided. This question is a combination problem. If K is definite, it will solve the problem by giving a loop without any difficulty. However, the difficulty lies in the uncertainty of K, so the number of layers of the loop cannot be determined. In this way, the K-cycle Traversal method cannot be used to solve the problem.
Recursion can solve this problem, and any recursive algorithm has a non-recursive algorithm implementation. So we will discuss these two algorithms separately.
Recursive Implementation:
Principle:
Recursive description:
If one value is taken from set a, recursion ends.
If the value retrieved from set a is greater than one, then after a is retrieved, refactored set a as B, recursively executed (B, k-1 );
Code:
# Include <iostream>
# Include <vector>
Using namespace STD;
Class solution {
Public:
Vector <vector <int> RS;
Vector <vector <int> combine (int n, int K ){
Vector <int> nn;
Vector <int> surplus;
For (INT I = 1; I <= N; I ++ ){
Surplus. push_back (I );
}
COM (NN, surplus, n, k );
Return Rs;
}
Void COM (vector <int> newsur, vector <int> surplus, int N, int K ){
If (k = 1 ){
For (INT I = 0; I <surplus. Size (); I ++ ){
Vector <int> temp = newsur;
Temp. push_back (surplus [I]);
Rs. push_back (temp );
}
} Else {
For (INT I = 0; I <= n-k; I ++ ){
Vector <int> temp = newsur;
Temp. push_back (surplus [I]);
Vector <int> last;
For (Int J = I + 1; j <surplus. Size (); j ++ ){
Last. push_back (surplus [J]);
}
COM (temp, last, last. Size (), k-1 );
}
}
}
};
Int main (){
Cout <"Hello World" <Endl;
Solution SL;
Vector <vector <int> rs = SL. Combine (4, 2 );
For (INT I = 0; I <Rs. Size (); I ++ ){
Cout <"{";
For (Int J = 0; j <Rs [I]. Size (); j ++)
{
Cout <Rs [I] [J];
If (J! = Rs [I]. Size ()-1)
Cout <",";
}
Cout <"}" <Endl;
}
// Getchar ();
Return 1;
}