日期:2014-05-18  浏览次数:20712 次

算法题:100分,给出任意长度数字字符串,求所有不重复的组合
比如输入字符串 "1234 ",   输出所有的不重复的24个组合:1234,1243,1324,1342。。。。。。,
输入字符串 "123 ",   输出所有的不重复的9个组合:123,132,213,。。。。。。

提示:
第一步:求出给定字符串的所有不重复组合数,比如 "1234 "的组合是24个, "123 "是9个, "1233 "是9个,
第二步:用到Hashtable和collections.shuffle()

如果不用上面的提示用其它的方法也行


------解决方案--------------------
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Enumeration;

public class TestString{
public static void main(String[] args){
Hashtable ht = new Hashtable();
int num1 = 0;
int num2 = 0;
int num3 = 1;
int num4 = 0;
String str = "123 ";

num2 = str.length();

for(;num2> 0;num2--){
num3 *= num2;
}
System.out.println(num3);
char[] ch = new char[str.length()];
str.getChars(0,str.length(),ch,0);
List list = new ArrayList();
for(int num=0;num <ch.length;num++){
list.add(new String(ch[num]+ " "));
}


while(num4 <num3){
Collections.shuffle(list);
Iterator it = list.iterator();
StringBuffer sb = new StringBuffer( " ");
while(it.hasNext()){
sb.append(it.next());
}
ht.put(sb.toString(), " ");
num4 = ht.size();
}

Enumeration e = ht.keys();
while(e.hasMoreElements()){
System.out.println(e.nextElement());
}
}
}
------解决方案--------------------
友情顶贴