昨天看到个帖子, 然后想了想写出一段程序来. 有空该补补排列组合的知识了.
1 /**
2 * 各字符不重复的组合, 组合数小于等于最大可能性(否则就重复了).
3 *
4 * @author scud(飞云)
5 */
6 public class ShortCombineTest
7 {
8 static int count = 0;
9
10 public static void main(String[] args)
11 {
12 String s = "123456"; //all items content
13 int howmany = 3; //how many object
14
15 char[] c = s.toCharArray();
16 char[] dest = new char[howmany];
17
18 combine(c, dest, howmany, s.length(), 0);
19
20 System.out.println("max combine:" + count);
21 }
22
23 public static void combine(char[] array, char[] dest, int howmany, int maxitem, int index)
24 {
25 //break & end
26 if (index == howmany)
27 {
28 System.out.println(dest);
29 count++;
30 return;
31 }
32
33 while(array.length>0)
34 {
35 dest[index] = array[0];
36 char[] nextarray = getLeftChar(array, 0);
37 array = nextarray;
38 combine(nextarray, dest, howmany, maxitem, index + 1);
39 }
40 }
41
42 public static char[] getLeftChar(char[] c, int index)
43 {
44 char[] left = new char[c.length - 1];
45
46 for (int i = 0, j = 0; i < c.length; i++)
47 {
48 if (i != index)
49 {
50 left[j] = c[i];
51 j++;
52 }
53 }
54
55 return left;
56 }
57
58
59 }
60