设为首页 加入收藏

TOP

LeetCode77:Combinations
2015-11-21 00:59:02 来源: 作者: 【 】 浏览:2
Tags: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

给定一个数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(); } } };
       
      
     
    
   
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇POJ2029:Get Many Persimmon Tree.. 下一篇poj 3537Crosses and Crosses 博..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: