输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。 结果请按字母顺序输出。
import java.util.ArrayList; import java.util.Collections; public class Solution { public ArrayList<String> Permutation(String str) { ArrayList<String> res = new ArrayList<String>(); if (str != null && str.length() > 0) { PermutationHelper(str.toCharArray(), 0, res); Collections.sort(res); } return res; } private static void PermutationHelper(char[] cs, int position, ArrayList<String> list) { if (position == cs.length - 1) { // 解空间的一个叶节点 list.add(String.valueOf(cs)); // 找到一个解 } else { for (int j = position; j < cs.length; ++j) { if (j == position || cs[j] != cs[position]) { swap(cs, position, j); PermutationHelper(cs, position + 1, list); swap(cs, position, j); // 复位 } } } } private static void swap(char[] cs, int i, int j) { char temp = cs[i]; cs[i] = cs[j]; cs[j] = temp; } }