【问题标题】:How can I find all possible letter combinations of a string?如何找到字符串的所有可能字母组合?
【发布时间】:2011-07-29 15:50:06
【问题描述】:

我得到一个字符串,我需要找到该字符串所有可能的字母组合。我可以实现这一目标的最佳方法是什么? 示例:

abc

结果:

abc
acb
bca
bac
cab
cba

到目前为止我什么都没有。我不是要代码。我只是在问最好的方法吗?算法?伪代码?也许是讨论?

【问题讨论】:

  • std::next_permuatation 如果你使用 c++ 应该可以解决问题
  • 严格来说,这些是排列,其中有n!:n * (n-1) * (n-2) * ... * 1

标签: algorithm pseudocode


【解决方案1】:

您可以对其进行排序,然后使用 std::next_permutation

看一下例子:http://www.cplusplus.com/reference/algorithm/next_permutation/

【讨论】:

    【解决方案2】:

    您想要组合还是排列?例如,如果您的字符串是“abbc”,您希望看到“bbac”一次还是两次?

    如果您真的想要排列,您可以使用std::next_permutation,它会为您处理所有工作。

    【讨论】:

    • 我想看一次 bbac...那我的问题叫什么?
    • 您需要组合,而不是字符串的排列。 :)
    【解决方案3】:

    如果您想要组合(顺序无关),您可以使用组合查找算法,例如找到here 或here。或者,您可以使用this(组合生成器的 java 实现,并通过示例演示您想要的内容。

    或者,如果您想要在帖子中列出的内容(排列),那么您可以(对于 C++)使用 <algorithm.h> 中的 std::next_permutation。你可以在std::next_permutationhere找到更多信息。

    希望这会有所帮助。 :)

    【讨论】:

      【解决方案4】:

      在 C++ 中,std::next_permutation:

      std::string s = "abc";
      do
      {
        std::cout << s << std::endl;
      } while (std::next_permutation(s.begin(), s.end()));
      

      【讨论】:

        【解决方案5】:

        从旧的维基百科文章中复制;

        对于每个数字 k,0 ≤ k

        function permutation(k, s) {
             for j = 2 to length(s) {
                swap s[(k mod j) + 1] with s[j]; // note that our array is indexed starting at 1
                k := k / j;        // integer division cuts off the remainder
             }
             return s;
        }
        

        【讨论】:

          猜你喜欢
          • 2015-03-09
          • 2020-07-01
          • 2017-11-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-29
          • 2015-05-06
          相关资源
          最近更新 更多