以下のコードは、すべての 3 文字の単語 (辞書式順序) を再帰的に生成しますstd::vector< std::vector<int> >
。各文字は 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の出力