LeetCode: Combinations

Source: Internet
Author: User

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 ;}};
    
   
  


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.