题目描述:输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输
入字符串 abc, 则打印出由字符 a,b,c 所能排列出来的所有字符串 abc,acb,bac,bca,cab 和 cba 。 思路 :将当前位置的字符和前一个字符位置交换,递归。public class Test {
public static void main(String[] args) {
char[] chars = {'a', 'b', 'c'};
List<String> resList = new ArrayList<>();
permute(chars,0,resList);
System.out.println(resList.stream().sorted().collect(Collectors.toList()));
}
public static void permute(char[] chars, int index, List<String> resList) {
if (index == chars.length - 1) {
resList.add(String.valueOf(chars));
return;
}
for (int i = index; i < chars.length; i++) {
if (i == index || chars[index] != chars[i]) {
swap(chars, index, i);
permute(chars, index + 1, resList);
swap(chars, index, i);
}
}
}
public static void swap(char[] chars, int i, int j) {
char c = chars[i];
chars[i] = chars[j];
chars[j] = c;
}
}