先說一下全排列:
對于R={r1,r2,…,rn},進行n個元素的全排列,設Ri=R – {ri}。結合X元素的全排列記為Perm(X),(ri)Perm(X)表示在全排列Perm(X)的每個排列前面加上前綴ri的得到的序列。R的全排列可歸納定義如下:
n=1時,Perm(R)=(r),其中r是R中的唯一元素;
n>1時,Perm(R)由(r1)Perm(R1), (r2)Perm(R2),…, (rn)Perm(Rn)構成。
顯然,部分排列,只要控制遞歸結束條件即可。
再說組合:
組合與排列相比,忽略了元素的次序,因此我們只需將元素按編號升序排列(或則其他的規則)即可。
代碼如下:


public class Main
{
static int count;

public static void main(String[] args)
{

int a[] =
{1, 2, 3, 4};
count = 0;
permutation(a, 0, 4);
System.out.println("count=" + count);
count = 0;
combination(a, 0, 3, 0);
System.out.println("count=" + count);
}

static void combination(int a[], int nowp, int m, int left)
{//zuhe

/**//*
* 求a[]中m個元素的組合
* nowp表示當前已經組合好的元素的個數
* left,只能選擇編號為left和它之后的元素 進行交換
*/

if(nowp == m)
{
count++;

for(int i = 0; i < m; i++)
{
System.out.print(a[i] + " ");
}
System.out.println();
}

else
{

for(int i = left; i < a.length; i++)
{
swap(a, nowp, i);
combination(a, nowp + 1, m, i + 1);
swap(a, nowp, i);
}
}
}

static void permutation(int a[], int nowp, int m)
{// pailie

/**//*
* 求a[]m個元素的排列
* nowp,當前已經排列好的元素的個數
*/

if(nowp == m)
{
count++;

for(int i = 0; i < m; i++)
{
System.out.print(a[i] + " ");
}
System.out.println();
}

else
{

for(int i = nowp; i < a.length; i++)
{
swap(a, i, nowp);
permutation(a, nowp + 1, m);
swap(a, i, nowp);
}
}
}

static void swap(int a[], int n, int m)
{
int t = a[n];
a[n] = a[m];
a[m] = t;
}

}

posted on 2013-07-06 10:54
小鼠標 閱讀(1326)
評論(0) 編輯 收藏 引用 所屬分類:
Java基礎練習