【发布时间】:2014-11-13 07:41:10
【问题描述】:
我想打印出长度为n 的所有可能的单词(为测试其他算法生成输入),其中包含从'a' 到'a' + n 的(可能重复的)字母。
我尝试执行以下操作:
#include <iostream>
#include <string>
#include <algorithm>
using size_type = std::size_t;
using symbol_type = std::string;
using char_type = typename symbol_type::value_type;
template< size_type n >
struct test
{
static_assert(!(size_type('z' - 'a') + 1 < n));
void
print(symbol_type const & _symbol) const
{
for (size_type i = 0; i < n; ++i) {
std::cout << _symbol.substr(i * n, n) << std::endl;
}
std::cout << std::endl;
}
bool
operator () () const
{
symbol_type mishmash_;
for (size_type i = 0; i < n; ++i) {
mishmash_.append(symbol_type(n, char_type('a' + i)));
}
print(mishmash_);
while (std::next_permutation(std::begin(mishmash_), std::end(mishmash_))) {
print(mishmash_);
}
return true;
}
};
int
main()
{
test< 3 > const test_{};
if (test_()) {
std::cout << "Succes!" << std::endl;
return EXIT_SUCCESS;
} else {
std::cerr << "Failure!" << std::endl;
return EXIT_FAILURE;
}
}
但是有重复的单词。如何以最优化的方式实现期望?
【问题讨论】:
-
您不需要
next_permutation,因为您已经说过字母可能重复。 -
@MohitJain 我确定我需要类似于
next_permutation的东西,STL 中没有类似的功能(在某种意义上除了random_suffle)。如您所见,我打印出整个字符串(长度为n * n)的子字符串(长度 =n),其中包含每个字母的n重复项。 -
您正在创建字符串
aaabbbccc并打印其排列的前 3 个字符。当前 3 个字符相同但其余字符重复时,您无法区分字符串。所以在这里你可以在没有 STL 的情况下工作得更好。 (例如递归和回溯) -
可以通过
n嵌套for循环来实现。 -
您也可以使用 1 for 循环来实现它。或者使用
std::set来跟踪已经打印的组合,不要再打印了。
标签: c++ stl permutation