如何实现排列组合,比如字符串"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);
}
}
字符串排列组合算法
本文介绍了一种通过递归构建树的方式实现字符串的所有可能排列组合的方法,并提供了完整的Java代码示例。该方法通过去除已选择字符逐步缩小组合范围,最终得到所有组合。
311

被折叠的 条评论
为什么被折叠?



