题目:输入一个字符串,打印出该字符串中字符的所有的排列。例如输入字符串abc,则打印出由字符a、b、c所能排列出来的所有字符串。
解题思路:把字符串分为两部分,一部分是字符串的第一个字符,另一部分是第一个字符以后的所有字符。接下来求第一个字符以后的所有字符的排列。拿第一个字符和它后面的字符串逐个交换。
C#实现:
public static void Permutation(char[] pStr) { if (pStr == null) return; int begin = 0; Permutation(pStr, begin); } private static void Permutation(char[] pStr, int begin) { if (begin == pStr.Length) Console.WriteLine(pStr); else { for (int i = begin; i < pStr.Length; i++) { char temp = pStr[i]; pStr[i] = pStr[begin]; pStr[begin] = temp; Permutation(pStr, begin + 1); temp = pStr[i]; pStr[i] = pStr[begin]; pStr[begin] = temp; } } }
Java实现:
public static void permutation(char[] pStr) { if (pStr == null) return; int begin = 0; permutation(pStr, begin); } private static void permutation(char[] pStr, int begin) { if (begin == pStr.length) System.out.println(pStr); else { for (int i = begin; i < pStr.length; i++) { char temp = pStr[i]; pStr[i] = pStr[begin]; pStr[begin] = temp; permutation(pStr, begin + 1); temp = pStr[i]; pStr[i] = pStr[begin]; pStr[begin] = temp; } } }
Python实现:
def permutation(pStr): if pStr == None: return begin = 0 permutation_child(pStr, begin) def permutation_child(pStr, begin): if begin == len(pStr): print(pStr) else: for i in range(begin, len(pStr)): temp = pStr[i] pStr[i] = pStr[begin] pStr[begin] = temp permutation_child(pStr, begin + 1) temp = pStr[i] pStr[i] = pStr[begin] pStr[begin] = temp