下面的代码将递归生成std::vector< std::vector<int> >
所有 3 个字母的单词(按字典顺序),其中每个字母来自一个 4 个字母的字母表。有64 = 4^3
这样的话。
请注意,一个简单的双循环是不够的,您需要对单词中的每个字母进行递归,并且对于每个字母,您都需要一个循环。总复杂度是O(K^N)
针对字母字母表中的N
字母单词K
,而不是O(K*N)
双循环。
它以一种直接的方式从 4 个字母的字母表中概括为 20 个字母的单词(尽管那是 2^40 = 1e12 个不同的单词)。当然,将它们与您的原始字符串匹配是一种简单的方式。
#include <array>
#include <cstddef>
#include <vector>
#include <iostream>
template<typename T, int K, int N>
void generate_all_multisets(
std::array<T, K> const& alphabet,
std::vector< std::vector<T> >& all_words,
std::vector<T>& current_word,
int current_letter
)
{
if (current_letter == N) {
all_words.push_back(current_word);
for (auto k = 0; k != N; ++k)
std::cout << current_word[k];
std::cout << "\n";
return;
}
auto const tmp = current_word[current_letter];
for (auto letter = alphabet.begin(); letter != alphabet.end(); ++letter) {
current_word[current_letter] = *letter;
generate_all_multisets<T, K, N>(alphabet, all_words, current_word, current_letter + 1);
}
current_word[current_letter] = tmp;
}
template<typename T, int K, int N>
void generate_all_words(
std::array<T, K> const& alphabet,
std::vector< std::vector<T> >& all_words
)
{
// first word
std::vector<T> word(N, alphabet.front());
generate_all_multisets<T, K, N>(alphabet, all_words, word, 0);
}
int main()
{
std::array<int, 4> alphabet = { 1, 2, 3, 4};
auto const word_length = 3;
std::vector< std::vector<int> > all_words;
generate_all_words<int, 4, 3>(alphabet, all_words);
return 0;
}
编辑:Ideone上的输出