Topic: 100分,给出任意长度数字字符串,求所有不重复的组合

  Print this page

1.100分,给出任意长度数字字符串,求所有不重复的组合 Copy to clipboard
Posted by: ruadergo
Posted on: 2007-07-20 19:43

比如输入字符串"1234", 输出所有的不重复的24个组合:1234,1243,1324,1342。。。。。。,
输入字符串"123", 输出所有的不重复的9个组合:123,132,213,。。。。。。

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

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

2.Re:100分,给出任意长度数字字符串,求所有不重复的组合 [Re: ruadergo] Copy to clipboard
Posted by: Cappuccino
Posted on: 2007-07-29 20:29

随便写了一个,勉强能用^_^

public class Pailie2
{
static List<String> usrInput = new LinkedList<String>();
static List<String> result = new LinkedList<String>();
public static void main(String[] args)
{
String str = "abcde";
init(str);
System.out.println(usrInput.size());
calc(str.length(),usrInput,"");
int count = 0;
for (String elem : result)
{
System.out.println(elem);
count++;
}
System.out.println("count:"+count);
}

//将用户输入的字符串装入到一个usrInput的list里面
public static void init(String str)
{
Set<Character> set = new HashSet<Character>();
for (int i = 0; i < str.length(); i++)
{
set.add(str.charAt(i));
}
for (Iterator it = set.iterator(); it.hasNext();)
{
Character elem = (Character)it.next();
usrInput.add(elem+"");
}
}

public static void calc(int maxlen,List<String> list,String prefix)
{
for (int i = 0; i < list.size(); i++)
{
String currentUnit = list.get(i);
if((prefix+currentUnit).length()==maxlen)
{
result.add(prefix+currentUnit);
}else
{
List<String> leftlist = new LinkedList<String>();
leftlist.addAll(list);
leftlist.remove(i);
calc(maxlen,leftlist,prefix+currentUnit);
}
}
}

}


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923