1、题目描述:
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输 入字符串 abc,则打印出由字符 a,b,c 所能排列出来的所有字符串 abc,acb,bac,bca,cab 和 cba。
*递归求解
2、代码
package com.ypj.java;
import java.util.ArrayList;
import java.util.Collections;
public class Permutation {
public ArrayList<String> permutation(String str){
ArrayList<String> res = new ArrayList<>();
if(str == null || str.length() == 0){
return res;
}
helper(res, 0, str.toCharArray());
Collections.sort(res);
return res;
}
public void helper(ArrayList<String> res, int index, char[] s){
if(index == s.length-1){
res.add(String.valueOf(s));
return;
}else{
for(int i=index; i<s.length;i++){
if(i == index || s[i] != s[index]){
swap(s, i, index);
helper(res, index+1, s);
swap(s,i,index);
}
}
}
}
public void swap(char[] c, int a, int b){
char temp = c[a];
c[a]=c[b];
c[b]=temp;
}
public static void main(String[] args) {
String str = "abc";
Permutation permutation = new Permutation();
System.out.println(permutation.permutation(str));
}
}
3、运行结果