【问题标题】:How to print all permutations of a number [duplicate]如何打印数字的所有排列[重复]
【发布时间】:2019-01-10 17:23:18
【问题描述】:

谁能帮我写一个 C++ 代码,打印出给定数字的所有可能排列。

例如,如果数字 N = 123,则 {123, 132, 213, 231, 312, 321} 是可能的排列。

我研究过,只能找到字符串而不是整数的代码。

谢谢。

【问题讨论】:

  • 先将 int 转换为字符串,然后重用您找到的代码
  • 没有什么不同。
  • 您不必将字符串转换为整数。将'N'作为字符串就足够了
  • 我需要使用排列进行进一步的计算,所以我想我必须再次将它们转换为整数?

标签: c++ algorithm


【解决方案1】:

你可能会使用:

void display_permutation(std::size_t n)
{
    std::string s = std::to_string(n);
    std::sort(s.begin(), s.end());
    do {
        std::cout << s << std::endl;
    } while (std::next_permutation(s.begin(), s.end()));
}

Demo

【讨论】:

  • 谢谢。但我无法理解你的意思。你能详细说明你的代码吗?
  • 您不清楚哪些部分?您是否查看过 std::to_stringstd::sort 尤其是 std::next_permutation 的文档?
  • 现在知道了。谢谢!
猜你喜欢
  • 2015-08-03
  • 1970-01-01
  • 1970-01-01
  • 2020-12-26
  • 1970-01-01
  • 2020-05-03
  • 1970-01-01
  • 2020-06-26
  • 2016-02-24
相关资源
最近更新 更多