LeetCode77:Combinations

2015-11-21 00:59:02 · 作者: · 浏览: 5

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

给定一个数n,求1到n之间的所有的k个数的组合。
这个题目可以在纸上画下草图,明显可以用递归求解。递归的终止条件是k=0,并且由于需要将组合保存到集合vector中,还需要使用回溯法来保存数据。
runtime:8ms

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