LeetCode算法系列:77. Combinations

题目描述:

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

Example:

Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

算法实现:

思路比较简单,使用递归法,或者说是回溯的方法,

  • 从n中选取k个元素      <=>     从n-1中选取k个元素   +   (元素n 和 从 n-1中选取的k-1个元素)
  • 结束条件:如果n和k相等,只有一种方案;如果k=1,有n中方案,将n中的n个元素任选一个
class Solution {
public:    
    vector<vector<int>> combine(int n, int k) {
        vector<int> oneres;
        vector<vector<int>> res;
        if(n < k)return res;        
        recursive(res, oneres, n, k);
        return res;
    }
    void recursive(vector<vector<int>> &res, vector<int> &oneres, int n, int k){
        // cout << n << "," << k << endl;
        if(n == k){
            for(int i = 0; i < n; i ++)oneres.push_back(i + 1);
            res.push_back(oneres);
            for(int i = 0; i < n; i ++)oneres.pop_back();
        }
        //这个if的情况开始没有考虑在内,导致出现了memory limit exceeded的情况,因为在下一种情况中的recursive(res, oneres, n - 1, k - 1)会不断的循环下去,没有尽头,及递归没有出口
        else if(k == 1){
            for(int i = 0; i < n; i ++){
                oneres.push_back(i + 1);
                res.push_back(oneres);
                oneres.pop_back();
            }
        }
        else if(n > k){
            recursive(res, oneres, n - 1, k);
            oneres.push_back(n);
            recursive(res, oneres, n - 1, k - 1);
            oneres.pop_back();
        }
    }
};

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值