如何实现排列组合,比如字符串"abc",那么它的组合结果总共有6种,以下是我实现组合的代码,基本思路就是把这个组合的过程,当作构建一颗树,每条路都是一个组合,直至到叶子节点为止。
public class PermComb {
public int count =0;
public void permCombination(String str,String combValue){
String newStr="";
String newCombValue = "";
str = str == null ? "" : str;
combValue = combValue == null ? "" : combValue;
if(str.length()==1){
System.out.println(combValue+str);
count++;
return;
}
for(int i=0;i<str.length();i++){
//从剩余字符串中移除掉当前节点
newStr= str.substring(0,i)+str.substring(i+1);
newCombValue = combValue+str.charAt(i);
permCombination(newStr,newCombValue);
}
}
public static void main(String[] args) {
String key ="abc";
PermComb permComb = new PermComb();
permComb.permCombination(key,null);
System.out.println("总数: "+ permComb.count);
}
}