package com.louisgeek.price;
/**
* 排列和组合算法
* @author Administrator
*
*/
public class CaseTest {
public static void main(String[] args) {
int[] ia = { 1, 2, 3, 4, 5 };
int n = 4;
System.out.println("排列结果 : ");
permutation(ia, n);
System.out.println("组合结果 : ");
combination(ia, n);
}
public static void permutation(String s, int[] ia, int n) {
if (n == 1) {
for (int i = 0; i < ia.length; i++) {
System.out.println(s + ia[i]);
}
} else {
for (int i = 0; i < ia.length; i++) {
String ss = "";
ss = s + ia[i] + "";
// 建立没有第i个元素的子数组
int[] ii = new int[ia.length - 1];
int index = 0;
for (int j = 0; j < ia.length; j++) {
if (j != i) {
ii[index++] = ia[j];
}
}
permutation(ss, ii, n - 1);
}
}
}
public static void permutation(int[] ia, int n) {
permutation("", ia, n);
}
public static void combination(int[] ia, int n) {
combination("", ia, n);
}
public static void combination(String s, int[] ia, int n) {
if (n == 1) {
for (int i = 0; i < ia.length; i++) {
System.out.println(s + ia[i]);
}
} else {
for (int i = 0; i < ia.length - (n - 1); i++) {
String ss = "";
ss = s + ia[i] + ", ";
// 建立从i开始的子数组
int[] ii = new int[ia.length - i - 1];
for (int j = 0; j < ia.length - i - 1; j++) {
ii[j] = ia[i + j + 1];
}
combination(ss, ii, n - 1);
}
}
}
}
输出结果:
排列结果 :
1234
1235
1243
1245
1253
1254
1324
1325
1342
1345
1352
1354
1423
1425
1432
1435
1452
1453
1523
1524
1532
1534
1542
1543
2134
2135
2143
2145
2153
2154
2314
2315
2341
2345
2351
2354
2413
2415
2431
2435
2451
2453
2513
2514
2531
2534
2541
2543
3124
3125
3142
3145
3152
3154
3214
3215
3241
3245
3251
3254
3412
3415
3421
3425
3451
3452
3512
3514
3521
3524
3541
3542
4123
4125
4132
4135
4152
4153
4213
4215
4231
4235
4251
4253
4312
4315
4321
4325
4351
4352
4512
4513
4521
4523
4531
4532
5123
5124
5132
5134
5142
5143
5213
5214
5231
5234
5241
5243
5312
5314
5321
5324
5341
5342
5412
5413
5421
5423
5431
5432
组合结果 :
1, 2, 3, 4
1, 2, 3, 5
1, 2, 4, 5
1, 3, 4, 5
2, 3, 4, 5