LeetCode算法系列:77. Combinations

版权声明:由于一些问题,理论类博客放到了blogger上,希望各位看官莅临指教https://efanbh.blogspot.com/;本文为博主原创文章,转载请注明本文来源 https://blog.csdn.net/wyf826459/article/details/82886342

题目描述:

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

猜你喜欢

转载自blog.csdn.net/wyf826459/article/details/82886342