我获取子集的递归没有打印出正确的答案

My recursion of getting subset doesn't print out the right answer

我正在尝试实现一种方法来获取集合的所有子集。我理解这样做的逻辑。即 Subset(n) = n + Subset(n-1),但是我写的代码一直打印出错误的答案。这是我的代码:

void subset(vector<int> &input, vector<int> output, int current) {
    if (current == input.size()-1) {
        output.push_back(input[current]);
        print(output);
    }
    else {
        for (int i = current; i < input.size();i++) {
            output.push_back(input[i]);
            print(output);
            subset(input, output, i+1);
        }
    }
}

这是我得到的输出(输入是 {1,2,3}):

1 
1 2 
1 2 3 
1 2 3 
1 2 
1 2 3 
1 2 3

知道我哪里出错了吗?任何帮助将不胜感激!

  • 您总是从头打印输出:因此您永远不会在输出中看到 [2,3]、[2] 或 [3]
  • 您在两个地方有打印语句 - 因此输出重复

我认为这可以帮助你:

void subset(vector<int> &input, vector<int> output, int current) {
    static int n=0;
    if (current == input.size()) {
        cout<<n++<<":\t {";
        for(int i=0;i<output.size();i++) cout<<output[i]<<", ";
        cout<<"\b\b}\n";
    }
    else {
        subset(input, output, current+1); //exclude current'th item
        output.push_back(input[current]);
        subset(input, output, current+1); //include current'th item 
    }
}

第一次你可以这样称呼它:

int main()
{
    std::vector<int> inp, out;
    for(int i=0; i<5; i++) // for example {1,2,3,4,5}
        inp.push_back(i);
    subset(inp, out, 0);
    return 0;
}