递归方法代码实现:
/**
* 全排列
* @param input
* @return
*/
public static List<String> FullPermutation(String input){
List<String> list = new ArrayList<String>();
StringBuffer tmp = new StringBuffer();
for (int i = 0; i < input.length(); i++) {
RecursiveMethod(input, i, tmp);
}
return list;
}
/**
* 递归获取全排列所有可能
* @param inStr
* @param pos
* @param parentData
*/
public static void RecursiveMethod(String inStr,int pos,StringBuffer parentData){
StringBuffer res = new StringBuffer();
res.append(parentData);
res.append(inStr.charAt(pos));
inStr = deleteElement(inStr, pos);
if (inStr.length() == 0) {
System.out.println(res.toString());
return;
}
for (int i = 0; i < inStr.length(); i++) {
RecursiveMethod(inStr, i, res);
}
}
/**
* 删除已经添加过的字符
* @param inStr
* @param pos
* @return
*/
public static String deleteElement(String inStr,int pos){
StringBuffer outStr = new StringBuffer();
if (inStr != null) {
for (int i = 0; i < inStr.length(); i++) {
if (i != pos) {
outStr.append(inStr.charAt(i));
}
}
}
return outStr.toString();
}
public static void main(String[] args) {
String inStr = "abcdefg";
for (int i = 0; i < inStr.length(); i++) {
FullPermutation(inStr);
}
}