使用deque和递归C++创建所有可能的组合

Create all possible combinations using a deque and recursion C++

本文关键字:有可能 组合 创建 C++ deque 递归 使用      更新时间:2023-10-16

我有一个包含一系列数字{0, 1, 2, 3, 4, 5, 6}的deque,我正在尝试使用递归创建这些数字的所有可能组合。

这是我当前的代码

void combination(vector<node> &comb, deque<node> &numbers) {
    if (numbers.empty()) {
        for (unsigned int i = 0; i < comb.size(); i++) {
            cout << comb[i].id << " ";
        }
        cout << "n";
        return;
    }
    comb.push_back(numbers.front());
    numbers.pop_front();
    combination(comb, numbers);
    comb.pop_back();
    combination(comb, numbers);
}

我已经在纸上运行过了,这是有道理的,但当我运行它时,这是输出:

0 1 2 3 4 5 6
0 1 2 3 4 5
0 1 2 3 4
0 1 2 3
0 1 2
0 1
0

为什么函数没有打印出所有可能的组合?

这也是我想要使用的-一个包含数字的deque和一个包含每个组合的向量。

您正在使用Pass by reference,我做了一些小的更改,它可以

代码:

#include <bits/stdc++.h>
using namespace std;
void combination(vector<int> comb, deque<int> numbers) {
    if (numbers.empty()) {
        for (unsigned int i = 0; i < comb.size(); i++) {
            cout << comb[i] << " ";
        }
        cout << "n";
        return;
    }
    comb.push_back(numbers.front());
    numbers.pop_front();
    combination(comb, numbers);
    comb.pop_back();
    combination(comb, numbers);
}
int main() {
    // your code goes here
    vector<int> comb;
    deque<int> numbers;
    for(int i = 0;i < 7;i++) numbers.push_back(i);
    combination(comb, numbers);
    return 0;
}

链接到ideone上的解决方案:http://ideone.com/vgukF3