java排列和组合算法

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
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值