LeetCode77: Combinations

Source: Internet
Author: User

LeetCode77: Combinations

Given two 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, 2],
[1, 3],
[1, 4],
]
Hide Tags Backtracking

Given a number n, evaluate the combination of all k numbers between 1 and n.
You can draw a sketch on the paper, which can be solved recursively. The recursive termination condition is k = 0. Because the combination needs to be saved to the set vector, backtracking is also required to save the data.
Runtime: 8 ms

class Solution {public:    vector
  
   > combine(int n, int k) {        vector
   
    > result;        vector
    
      vec;        helper(1,n,k,vec,result);        return result;    }    void helper(int first,int last,int k,vector
     
       & vec,vector
      
       > & result) { if(k==0) { result.push_back(vec); return ; } for(int i=first;i<=last-k+1;i++) { vec.push_back(i); helper(i+1,last,k-1,vec,result); vec.pop_back(); } }};
      
     
    
   
  

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.