生成所有未知长度的组合

Generating all combinations with unknown length

本文关键字:组合 未知      更新时间:2023-10-16

我正在练习编程,我用c++生成所有的组合。我知道如何生成所有的组合一定的长度结果是这样的

A A A
A A B
A A C
A B A
A B B
A B C
A C A
A C B
A C C
B A A
..... 

我的问题是,我不知道,如何生成未知长度的所有组合。例如,我想要单词长度= 5,程序将生成长度为5的所有组合。怎么做呢?

A A A A A
A A A A B
A A A A C
A A A B A
.........

(对不起我的英文)

查看链接打印所有重复字符的排列

下面的递归函数在页面中,可以创建最后+1个长度的排列。

/* The main function that recursively prints all repeated 
permutations of  the given string. It uses data[] to store all
permutations one by one */
void allLexicographicRecur (char *str, char* data, int last, int index)
{
  int i, len = strlen(str);
  // One by one fix all characters at the given index and recur for 
  // the/ subsequent indexes
  for ( i=0; i<len; i++ )
  {
      // Fix the ith character at index and if this is not the last 
      // index then recursively call for higher indexes
      data[index] = str[i] ;
     // If this is the last index then print the string stored in
     // data[]
     if (index == last)
         printf("%sn", data);
     else // Recur for higher indexes
        allLexicographicRecur (str, data, last, index+1);
  }
}

我想这可以达到你的目的。调用allLexicographicRecur,使用'last'参数所需的(长度-1)值

这实际上只是计数

如果你有字母A, B和C,你是以3为基数计数的。
A为0,B为1,C为2。

又快又脏:

#include <string>
#include <iostream>
int main()
{
    for(int i = 0; i < 100; i++) {
        const int base = 3;
        const char zero_char = 'A';
        const size_t length = 5;
        std::string out;
        for(int n = i; n > 0; ) {
            int d = n%base;
            out = static_cast<char>(zero_char + d) + out;
            n /= base;
        }
        while(out.length() < length) out = zero_char + out;
        std::cout << out << 'n';
    }
}

看现场


可能的组合是基数长度,因此如果您希望A, B, C的所有组合都是5位数字,则将第一个for循环的限制更改为35 (= 243):

for(int i = 0; i < 243; i++)

你可以这样写:

bool increase(const std::string& s, std::vector<std::size_t>& it)
{
    for (std::size_t i = 0, size = it.size(); i != size; ++i) {
        const std::size_t index = size - 1 - i;
        ++it[index];
        if (it[index] >= s.size()) {
            it[index] = 0;
        } else {
            return true;
        }
    }
    return false;
}
void do_job(const std::string& s,
            const std::vector<std::size_t>& it)
{
    for (std::size_t i = 0; i != it.size(); ++i) {
        std::cout << s[it[i]] << " ";
    }
    std::cout << std::endl;
}
void cartesian_product(const std::string& s, std::size_t n)
{
    std::vector<std::size_t> it(n, 0u);
    do {
        do_job(s, it);
    } while (increase(s, it));
}
演示