字符串组合

来源:互联网 发布:java 环境变量配置 编辑:程序博客网 时间:2024/05/20 12:48

声明:本篇文章为学习何海涛的网易日志后,自己的学习总结。

题目:输入一个字符串,输出该字符串中字符的所有组合。举个例子,如果输入abc,它的组合有abcabacbcabc

思路:使用递归算法,假如我们要在low,high之间找长度为n的字符组合,当遇到low的字符,如果low位置的字符加入到组合时,只需要在low+1,high之间找到n-1位字符的组合,如果low位置的字符不加入到组合中,则只需要在low+1,high之间找到n位字符的组合。

public class Combination {public static void main(String[] args){String str = "abcd";int length = str.length();Vector<Character> vec = new Vector<Character>();for(int i=1;i<=length;i++){combination(str.toCharArray(),0,length-1,i,vec);}}public static void combination(char[] c, int low, int high, int length,Vector<Character> vec){if(c==null) //如果字符数组为空return ;if(length==0){for(int i=0;i<vec.size();i++)       System.out.print(vec.elementAt(i));System.out.println();return ;}if(low>high || (high-low+1)<length)  //当出现不可能的情况时及时停止return ;else{combination(c,low+1,high,length,vec); //low位置的字符不算vec.add(c[low]);//将low位置的字符加入combination(c,low+1,high,length-1,vec);vec.remove(vec.size()-1);}}}


1 0
原创粉丝点击