設有三組集合,在以下每組中取出一個數
{A,B,C}
{D,E,F}
{G,H,I}
可以得到27組 {A,D,G}{A,D,H}{A,D,I}{A,E,G}{A,E,H}{A,E,I}....
public class Permutation
{
static int index = 1;
static int MAX = 3; // 用來產生 3*3, 改成4就是4*4, 5*5 6*6....
static char[] soultion = new char[MAX]; // 用來紀錄排列解.
static char[][] s = new char[MAX][MAX]; // 陣列.
static boolean[][] used = new boolean[MAX][MAX]; // 紀錄這個數字是否被使用.
static void perm(int k, int h, int n)
{
if (k == n)
{
System.out.print("序號" + (index++) + ":");
for (char s : soultion)
{
System.out.print(s + "\t");
}
System.out.println();
}
else
{
for (int i = 0; i < n; i++)
{
if (!used[h][i])
{
used[h][i] = true;
soultion[k] = s[h][i];
perm(k+1, h+1, n);
used[h][i] = false;
}
}
}
}
public static void main(String[] args)
{
// 純粹產生排列陣列字元.
System.out.println("陣列:");
int c = 65;
for (int i = 0; i < MAX; i++)
{
for (int j = 0; j < MAX; j++)
{
used[i][j] = false;
s[i][j] = (char) (c++);
}
}
// Print 字元.
for(char[] ss : s)
{
for (char ch : ss)
{
System.out.print(ch);
}
System.out.println();
}
perm(0, 0,MAX);
}
}
0 意見:
張貼留言