[leetcode] combination (不会做)

本文介绍了一种使用队列和向量实现的算法,该算法能够高效地生成从1到n的所有可能k个数的组合。通过具体的示例展示了当n为4且k为2时所有可能的组合,并提供了完整的C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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],
]

class Solution {
public:
    vector<vector<int> > combine(int n, int k) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        assert(n>=k);
        assert(k>0);
    
        vector<vector<int> >results;
        queue<vector<int> >temp;
        temp.push(vector<int>());
        while(!temp.empty()){
            vector<int> current= temp.front();
            temp.pop();
            int val;
            if (current.size()>0)
                val = current.at(current.size()-1);
            else
                val = 0;
            current.push_back(0);
            for(int i = val+1; i<= n; i++){
                current[current.size()-1]= i;
                if (current.size() == k)
                    results.push_back(current);
                else
                    temp.push(current);
            }
        }
        return results;
    }
};
1. 比DP做要简单的多,DP的代码弄了好久也没弄清楚

2. 注意queue的用法,以及vector中取最后一个值可以用back





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值