在 C++ 中创建蛮力算法

Creating a brute-force algorithm in C++

我正在尝试用 C++ 编写一个强力算法来解决问题。我之前在 Python 中做了一个蛮力算法,但这使用了第 3 方库,这意味着我无法将它转换为 C++。我很喜欢这个设计,我找到了;

#include <iostream>

using namespace std;

int main() {
    string characters = "abcde";

    int length = 5;
    string word = "";
    for(int i = word.length(); i <= length; i++) {
        for(int l = 0; l < characters.length(); l++) {
            word += characters[l];
            cout << word << "\n";
        }
    }
    return 0;
}

,但由于一些错误,它的输出是:

abcdeabcde
abcdeabcdea
abcdeabcdeab
abcdeabcdeabc
abcdeabcdeabcd
abcdeabcdeabcde

等等... 我需要的结果是:

a
b
c
d
e
aa
ab
ac
ad
ae
ba
bb
bc
...

提前致谢:)

感谢任何帮助:)

您生成所有排列的方法存在根本性缺陷。即使您的代码中的错误得到修复,它也不会按照您想要的方式运行。

简单地说,使用 2 级循环,您永远不会遇到 "aaa" 排列。

我个人推荐递归方法,这里有一个您可以解决的粗略起点:

#include <iostream>
#include <string>

void visit(std::string const& chars, size_t max_len, std::string const& cur) {
    if(cur.length() == max_len) {
      return;
    }
    else {
      for(auto c : chars) {
        std::string next = cur + c;
        std::cout << next << std::endl;

        visit(chars, max_len, next);
      }
    }
}

int main() {
  visit("abcde", 5, "");
  return 0;
}