每个最后的组合都是双基本C ++

问题描述 投票:-1回答:2

我想要一个返回字母X的所有可能组合的函数,组合必须是n长。我知道这已经做了一百万次,但我试着理解递归。

我不明白的两件事:

一。该函数将系列的每个最后一次迭代插入两次,因此如果字母表为'AB'且长度为2,我会期望:

AA
AB
BA
BB

但我得到:

AA
AB
AB
BA
BB
BB

2.函数如何在外循环中需要返回。如果我只是删除外循环并离开返回然后我得到分段错误。

在函数中我保持向量与我,我也可以把它放在全局范围但我有相同的效果。我在运行中构建可能的组合S并保持len en深度:

#include<iostream>
#include<vector>
#include<cstring>
using namespace std;

void combirec(vector<string> &A, char S[20], char *alphabet, int len, int depth)
{
    for (int i = 0; i < len; i++) {
        for (int c = 0; c < strlen(alphabet); c++) {
            S[depth] = alphabet[c];
            combirec(A, S, alphabet, len-1, depth+1);
            A.push_back(S);
        }
        return;
    }
}

int main()
{
    vector<string> A;
    char S[20];
    char alphabet[6] = "AB";
    int len = 2;
    S[len] = '\0';
    combirec(A, S, alphabet, len, 0);
    for (int i = 0 ; i < A.size(); i++)
        cout << A[i] << endl;
}
c++ recursion cartesian-product
2个回答
1
投票

你的问题是有循环和递归:

void combirec(vector<string> &A, char S[20], char *alphabet, int len, int depth)
{
    for (int i = 0; i < len; i++) {//<--LOOP HERE
        for (int c = 0; c < strlen(alphabet); c++) //{<--LOOP HERE
            S[depth] = alphabet[c];
            combirec(A, S, alphabet, len-1, depth+1);//<--RECURSIVE HERE
            A.push_back(S);
        }
        return;
    }
}

如果你不想递归,你最多可能需要一个循环。

有关类似问题,请参阅此答案:

Creating all possible k combinations of n items in C++


1
投票

一些有用的建议导致了一个解决方案,虽然为什么这个工作对我来说仍然模糊。我自己也永远不会想出这个。

void combirec(vector<string> &A, char S[20], char *alphabet, int len, int depth)
{
    if (len > 0)
        for (int c = 0; c < strlen(alphabet); c++) {
            S[depth] = alphabet[c];
            combirec(A, S, alphabet, len-1, depth+1);
        }
    else
        A.push_back(S);

}
© www.soinside.com 2019 - 2024. All rights reserved.