LeetCode77. 组合

题目大意:求出1~n中所有可能的k个数的组合。

题目分析:本题使用递归求解比较简单,当固定第一个数“1”时,就相当于求解后面2~n中所有可能的k-1组合,然后一直到k等于0,表示一种组合情况已经得到,保存到res中即可。

代码展示:

class Solution {
public:
    vector<vector<int>> combine(int n, int k) {
        vector<vector<int>> res;
        vector<int> temp;
        if(n<k)
            return res;
        combineSolve(1,n,k,temp,res);
        return res;
    }
    
    void combineSolve(int begin,int end,int k,vector<int> &temp,vector<vector<int>> &res){
        if(k==0){
            res.push_back(temp);
            return;
        }
        for(int i=begin;i<=end;i++){
            temp.push_back(i);
            combineSolve(i+1,end,k-1,temp,res);
            temp.pop_back();
        }
    }
};

猜你喜欢

转载自blog.csdn.net/jaster_wisdom/article/details/81089372
今日推荐