且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用递归查找一组字符串中字符的所有可能排列

更新时间:2023-01-11 22:32:49

只需写下五个嵌套循环即可.在伪代码中,

Just write down the five nested loops. In pseudocode,

for a in "ἸἼΙἹἽ"
  for b in "ῇηἤήῃὴῆἡἠἢᾖἥἣῄἦᾗᾐἧᾔᾑ"
    for c in "σς"
      for d in "οὸόὀὄὅὂ"
        for e in "ὺὖυῦύὐὑὔΰϋὕὗὓὒῢ"
           emit [a,b,c,d,e]

用递归对这五个循环进行编码,所以它适用于任意数量的输入字符串,同样是伪代码,

To encode these five loops with recursion, so it's good for any number of input strings, again in pseudocode,

g(list-of-strings) =
   | case list-of-strings
   | of  empty --> end-of-processing
   | of  (first-string AND rest-of-strings) --> 
            for each ch in first-string 
               DO g(rest-of-strings)

现在你只需要弄清楚每个当前 first-string 的字符 ch 的保存位置,以及如何在 结束时将它们组合起来 -of-processing(基本上,您的两个选项是全局累加器或函数调用的参数).

Now you only need to figure out where to hold each current first-string's character ch and how to combine them all while at the end-of-processing (basically, your two options are a global accumulator, or an argument to a function invocation).