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],] solution: First, we convert the problem to {1, 2, 3 ,.... n} contains all subsets of k. generally, n values in the combination question are not too large, so I chose to use the binary bit of an int variable to mark an element and then enumerate it from 0 to (1 <n) -1, you can know all its subsets. Since the subset size is k, you need to determine that the number of 1 in the current enumeration value is k. this method is obviously feasible, but the time complexity is a little high O (2 ^ n). So, can we enumerate only the subset of the enumerated elements with the size of k? By using bitwise operations, we can easily achieve this. Solution code:Class Solution {public: vector
> Combine (int n, int k) {vector
> Res; int comb = (1 <k)-1; while (comb <1 <n) {int tmp = comb, cnt = 1; vector
Sub; while (tmp) {if (tmp & 1) sub. push_back (cnt); ++ cnt; tmp >>=1;} res. push_back (sub); // key code int x = comb &-comb, y = comb + x; comb = (comb &~ Y)/x> 1) | y;} return res ;}};