排列组合的模板算法

排列组合(百度百科)

排列组合是组合学最基本的概念。所谓排列,就是指从给定个数的元素中取出指定个数的元素进行排序。组合则是指从给定个数的元素仅仅取出指定个数的元素,不考虑排序。排列组合的中心问题是研究给定要求的排列和组合可能出现的情况总数。排列组合与古典概率论关系密切。

举例说明


//abc的排列
abc  acb  bac  bca  cba  cab
共有6种排序

//abc的组合
33的可能:abc
32的可能:ab  ac  bc
31的可能:a  b  c

排列模板代码

/**
 * @author god-jiang
 * @date 2020/3/23  14:31
 */
public class Permutation {
    //全排列
    public static void perm(char[] arr, int start, int len) {
        if (start == len - 1) {
            for (int i = 0; i < len; i++) {
                System.out.print(arr[i]);
            }
            System.out.println();
        } else {
            for (int i = start; i < len; i++) {
                swap(arr, start, i);
                perm(arr, start + 1, len);
                swap(arr, start, i);
            }
        }
    }

    //交换两个数
    public static void swap(char[] arr, int i, int j) {
        char temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public static void main(String[] args) {
        char[] arr = "abc".toCharArray();
        perm(arr, 0, arr.length);
    }
}

在这里插入图片描述


组合模板代码

import java.util.Arrays;

/**
 * @author god-jiang
 * @date 2020/3/23  14:57
 */
public class Combination {
    public static void combination (char[] input, char[] output, int index, int start) {
        if (index == output.length) {
            System.out.println(Arrays.toString(output));
        } else {
            for (int j = start; j < input.length; j++) {
                output[index] = input[j];
                combination (input, output, index + 1, j + 1);
            }
        }
    }

    public static void main(String[] args) {
        char[] input = "abc".toCharArray();
        //N表示组合中取几位数
        int N = 2;
        char[] output = new char[N];
        combination (input, output, 0, 0);
    }
}

在这里插入图片描述

PS:一般比赛或者笔试都可以直接当作模板来使用。就好比,蓝桥杯比赛和牛客网笔试要带输入输出模板一样。然后就是希望对你们有所帮助。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值