题目:
输入一个字符串,输出该字符串中字符的所有组合。举个例子,如果输入abc,它的组合有a、b、c、ab、ac、bc、abc。
分析:
假设我们想在长度为n的字符串中求m个字符的组合。我们先从头扫描字符串的第一个字符。针对第一个字符,我们有两种选择:一是把这个字符放到组合中去,接下来我们需要在剩下的n-1个字符中选取m-1个字符;而是不把这个字符放到组合中去,接下来我们需要在剩下的n-1个字符中选择m个字符。这两种选择都很容易用递归实现。
java代码实现:
private static void combination(String str) {
char[] chars = getChars(str);
Stack stack = new Stack();
for(int i=1;i<=chars.length;i++) {
combination(chars,0, i,stack);
}
}
private static void combination(char[]chars, int index, int number,Stack stack) {
if(number == 0) {
Iterator iterator = stack.iterator();
while(iterator.hasNext()) {
System.out.print(iterator.next());
}
System.out.print(" ");
return ; //如果不返回,则会出现重复的字符组合
}
if(index == chars.length)
return ;
stack.push(chars[index]);
combination(chars, index+1,number-1,stack);
stack.pop();
combination(chars, index+1,number,stack);
}
private static char[] getChars(String str) {
char[] temp = new char[str.length()];
for(int i=0;i<str.length();i++) {
temp[i] = str.charAt(i);
}
return temp;
}