算法题:100分,给出任意长度数字字符串,求所有不重复的组合
比如输入字符串 "1234 ", 输出所有的不重复的24个组合:1234,1243,1324,1342。。。。。。,
输入字符串 "123 ", 输出所有的不重复的9个组合:123,132,213,。。。。。。
提示:
第一步:求出给定字符串的所有不重复组合数,比如 "1234 "的组合是24个, "123 "是9个, "1233 "是9个,
第二步:用到Hashtable和collections.shuffle()
如果不用上面的提示用其它的方法也行
------解决方案--------------------递归阿
------解决方案--------------------这个比较简单高效吧,其实核心算法的代码只有10行左右。
import java.util.ArrayList;
public class CombinationComputer {
public static void printAllCombination( String s ) {
printAllCombination( toArray(s), " ", s.length() );
}
private static void printAllCombination( MyChar[] chars, String result, int totalChar ) {
if( totalChar <= 0 ) {
System.out.println( result );
return;
}
for( int i = 0, n = chars.length; i < n; i++ ) {
MyChar myCh = chars[i];
if( myCh.count_ > 0 ) {
myCh.count_--;
printAllCombination( chars, result + myCh.ch_, totalChar-1 );
myCh.count_ ++;
}
}
}
private static MyChar[] toArray( String s ) {
ArrayList <MyChar> chars = new ArrayList <MyChar> ();
for( int i = 0, n = s.length(); i < n; i++ ) {
char ch = s.charAt( i );
MyChar myCh = find( ch, chars );
if( myCh == null )
chars.add( new MyChar( ch ) );
else myCh.count_ ++;
}
return chars.toArray( new MyChar[0] );
}
private static MyChar find( char ch, ArrayList <MyChar> chars ) {
for( int i = 0, n = chars.size(); i < n; i++ ) {
MyChar myCh = chars.get( i );
if( myCh.ch_ == ch ) return myCh;
}
return null;
}
private static class MyChar {
char ch_;
int count_ = 0;
MyChar( char ch ) {
ch_ = ch;
count_ = 1;
}
}
public static void main( String[] args ) {
CombinationComputer.printAllCombination( "1233 " );
}
}