Understand Principles
Initial steps: For a single element, arrangement is the element itself.
Two elements:
<code>perm(a) -> a</code>
Three elements:
<code>perm(ab) -> a + perm(b) -> ab b + perm(a) -> ba</code>
The recursive algorithm in the pseudo code
C# implementation<code>perm(abc) -> a + perm(bc) -> abc, acb b + perm(ac) -> bac, bca c + perm(ab) -> cab, cba</code>
<code>generatePermutations(permutation) { if (permutation 的长度 为 0) { 打印 permutation 返回 } 对于 permutation 中的每个元素 element: 创建一个新的排列 newPermutation,移除 element 将 element 添加到 generatePermutations(newPermutation) 的结果的前面 }</code>
public static void GeneratePermutations(char[] list) { int x = list.Length - 1; GeneratePermutations(list, 0, x); } private static void GeneratePermutations(char[] list, int k, int m) { if (k == m) { Console.WriteLine(new string(list)); //输出排列 } else { for (int i = k; i <= m; i++) { Swap(list, i, k); GeneratePermutations(list, k + 1, m); Swap(list, i, k); // 回溯,恢复原始顺序 } } } private static void Swap(char[] list, int i, int j) { char temp = list[i]; list[i] = list[j]; list[j] = temp; }
The above is the detailed content of How Can Recursive Algorithms Generate All Permutations of Strings and Integers?. For more information, please follow other related articles on the PHP Chinese website!