在C+中创建蛮力算法+; 我试图用C++编写一个蛮力算法来解决问题。我以前在Python中制作了一个蛮力算法,但是使用了第三方库,这意味着我不能将它转换成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; }

在C+中创建蛮力算法+; 我试图用C++编写一个蛮力算法来解决问题。我以前在Python中制作了一个蛮力算法,但是使用了第三方库,这意味着我不能将它转换成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; },c++,algorithm,c++11,brute-force,C++,Algorithm,C++11,Brute Force,等等。。。 我需要的结果是: a b c d e aa ab ac ad ae ba bb bc ... 提前感谢:) 非常感谢您的帮助:)您生成所有排列的方法存在根本缺陷。即使代码中的bug已经修复,它也不会按照您想要的方式运行 简单地说,使用2级循环,您永远不会达到“aaa”排列 我个人推荐一种递归方法,这里有一个粗略的起点,您可以解决: #include <iostream> #include <string> void visit(std::string co

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

a
b
c
d
e
aa
ab
ac
ad
ae
ba
bb
bc
...
提前感谢:)


非常感谢您的帮助:)

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

简单地说,使用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;
}
#包括
#包括
无效访问(标准::字符串常量和字符、最大大小、标准::字符串常量和当前){
如果(当前长度()=最大长度){
回来
}
否则{
用于(自动c:chars){
std::string next=cur+c;

std::难道这不是你的代码输出吗?你想对该字符串进行所有可能的排列,等等……你不需要每次都遍历该字符串。我会使用一个字符数组来实现这一点。对于这个问题,更好的措辞是:“我想在给定字母表的语言中生成所有单词”(尽管我的措辞有点混乱)我非常喜欢这种递归方法:)我不是那种抄袭别人的作品并声称它是我自己的作品的人,我喜欢自己编程和学习,但我完全不懂。谢谢,伙计,这真的很有帮助!我不太使用堆栈溢出,我如何给你声誉分数?只需将我的答案标记为已接受()。很高兴能提供帮助。这取决于版本()。我使用的功能称为“基于范围的for循环”。根据该矩阵,它是在MSVC 2012中引入的。将我的代码更改为使用传统的for循环非常简单。我相信你可以从这里开始。
#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;
}