import java.util.List;<br />import java.util.ArrayList;<br />/**<br /> * 求字串的len組合數<br /> *<br /> * @author wenin819<br /> *<br /> */<br />public class Combination{<br />/**<br /> * 求組合數的主要方法<br /> */<br />public static List<String> combination(String inStr, int len){<br />StringBuffer noDoubleStr =new StringBuffer(inStr);<br />noDouble(noDoubleStr);<br />if( len >= noDoubleStr.length()) return null;<br />return combinationItem(noDoubleStr , len);<br />}<br />/**<br /> * 去除重複的字元<br /> */<br />public static void noDouble(StringBuffer input){<br />for(int i = 0; i < input.length(); i++){<br />char temp = input.charAt(i);<br />for(int j = i+1; j < input.length(); ){<br />if(temp == input.charAt(j)){<br />input.deleteCharAt(j);<br />}else{<br />j++;<br />}<br />}<br />}<br />}<br />/**<br /> * 求組合數<br /> */<br />public static List<String> combinationItem(StringBuffer input, int len){<br />List<String> rsList = new ArrayList<String>();<br />boolean[] array = new boolean[input.length()];<br />for(int i = 0; i < array.length; i++){<br />array[i] = false;<br />}<br />do{<br />if(len == countOfTrue(array)){<br />StringBuffer temp = new StringBuffer(input);<br />for(int j = temp.length() - 1;j >= 0;j--){<br />if(array[j]) continue;<br />temp.deleteCharAt(j);<br />}<br />rsList.add(new String(temp));<br />}<br />}while(booleanAdd(array));<br />return rsList;<br />}<br />/**<br /> * 求boolean數組元素為true的個數<br /> */<br />public static int countOfTrue(boolean[] array){<br />int count = 0;<br />for(int i = 0;i < array.length;i++){<br />if(array[i]) count++;<br />}<br />return count;<br />}<br />/**<br /> * boolean數組自加(同2進位加1)<br /> */<br />public static boolean booleanAdd(boolean[] array){<br />boolean flag = true;<br />for(int i = 0;i < array.length; i++){<br />if(false == flag) return true;<br />if(array.length-1 == i && true == array[i]){<br />array[i] = false;<br />return false;<br />}<br />if(false == array[i]){<br />array[i] = true;<br />return true;<br />}<br />array[i] = false;<br />}<br />return false;<br />}<br />public static void main(String[] args){<br />String input = new String("abcde");<br />int len = 3;<br />if(args.length > 1){<br />input = args[0];<br />len = Integer.parseInt(args[1]);<br />}<br />List list = combination(input,len);<br />if(list != null){<br />System.out.println(input+"的"+len+"組合數的個數為:"+list.size()+"/n組合數分別為:");<br />for(int i = 0; i < list.size(); i++){<br />System.out.println(i+1+": "+list.get(i).toString());<br />}<br />}<br />}<br />}<br />