有人可以给我一些线索或帮助编写组合函数,它会输出一组的所有可能组合。我有个主意。但我觉得很难。
Java中有类似的东西。
String set[] = {"Java","C++","Python"};
ArrayList<String> list = new ArrayList<String>();
public void combination(String[] set) {
if (set.length == 0) {
do nothing
} else if (this a combination from the set) {
add to the list
}
}
答案 0 :(得分:0)
这是一个字符串中所有字母组合的简单示例,只是为了给你一个算法。看看你是否可以将算法转移到你的例子中。
public class StringLib {
public static void combine(String str){
int length=str.length();
StringBuffer output=new StringBuffer();
combination(str,length,output,0);
}
static void combination(String str, int length, StringBuffer output, int level){
/* show arms-length recursion style with better peformance */
if (level==length)
return;
else{
for(int i=level;i<length;i++){
output.append(str.charAt(i));
System.out.println(output.toString());
combination(str,length,output,i+1);
output.deleteCharAt(output.length()-1);
}
}
}
public static void main(String[] args){
combine("abc");
}
}
/*Output:
a
ab
abc
ac
b
bc
c
*/
万一你真的需要排列:
import java.util.*;
public class permutations
{
public static void main(String[] args)
{
String str = new String("abc");
StringBuffer output = new StringBuffer();
boolean used[] = {false, false, false};
permute.printPermutations(0, output, used, str);
}
}
public class permute{
static void printPermutations(int level, StringBuffer output, boolean used[], String orig){
int len = orig.length();
if (level == len){
System.out.println(output);
}
else{
for (int i = 0; i < len; i++){
//recurse if not used already
if (!used[i]){
output.append(orig.charAt(i));
used[i] = true;
printPermutations(level+1, output, used, orig);
output.deleteCharAt(output.length() - 1);
used[i] = false;
}
}
}
}
}
/*Output:
abc
acb
bac
bca
cab
cba
*/