xinyu04

导航

LeetCode 77 Combinations 回溯

Given two integers \(n\) and \(k\), return all possible combinations of \(k\) numbers out of the range [1, n].

You may return the answer in any order.

Solution

依旧是使用回溯。和前面的所有子集不同的是,我们只需要保留 \(k\) 个元素即可

点击查看代码
class Solution {
private:
    vector<vector<int>> ans;
    vector<int> cur;
    
    
    void dfs(vector<vector<int>>& ans, vector<int>& cur, int n,int k, int st){
        if(cur.size()==k){
            ans.push_back(cur);return;
        }
        for(int i=st;i<=n;i++){
            cur.push_back(i);
            dfs(ans, cur, n,k, i+1);
            cur.pop_back();
        }
    }

public:
    vector<vector<int>> combine(int n, int k) {
        dfs(ans, cur, n, k, 1);
        return ans;
    }
};

posted on 2022-07-25 15:00  Blackzxy  阅读(17)  评论(0编辑  收藏  举报