写一个函数,例如:给你的 a b c 则输出 abc acb bac bca cab cba。
package com.ispeasant.note;
import java.util.ArrayList;
import java.util.List;
/**
*
* 写一个函数,例如:给你的 a b c 则输出 abc acb bac bca cab cba
*/
public class Demo {
public static void main(String[] args) {
String s = "abc";
List<String> result = list(s, "");
System.out.println(result.size());
System.out.println(result);
}
/**
* 列出所有组合
*
* @param base
* 以该字符串为基础,进行选择性组合
* @param buff
* 所求字符串的临时结果
* @return result 所求结果
*/
public static List<String> list(String base, String buff) {
List<String> result = new ArrayList<String>();
if (base.length() <= 0) {
result.add(buff);
}
// 遍历基础字符串,逐步改变字符串的位置
for (int i = 0; i < base.length(); i++) {
List<String> temp = list(new StringBuilder(base).deleteCharAt(i).toString(), buff + base.charAt(i));
result.addAll(temp);
}
return result;
}
}
运行结果:
6
[abc, acb, bac, bca, cab, cba]
代码下载:源码下载