java的排列组合 全排列 组合排列

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Java中实现排列组合的代码示例: ``` import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class PermutationCombination { // 计算阶乘 public static int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; } // 计算排列数 public static int permutation(int n, int r) { return factorial(n) / factorial(n - r); } // 计算组合数 public static int combination(int n, int r) { return permutation(n, r) / factorial(r); } // 递归实现全排列 public static void permutation(List<Integer> nums, int start, List<List<Integer>> result) { if (start == nums.size()) { result.add(new ArrayList<>(nums)); return; } for (int i = start; i < nums.size(); i++) { swap(nums, start, i); permutation(nums, start + 1, result); swap(nums, start, i); } } // 交换数组中两个元素的位置 public static void swap(List<Integer> nums, int i, int j) { int temp = nums.get(i); nums.set(i, nums.get(j)); nums.set(j, temp); } public static void main(String[] args) { List<Integer> nums = Arrays.asList(1, 2, 3); // 计算排列数和组合数 System.out.println("permutation: " + permutation(5, 3)); System.out.println("combination: " + combination(5, 3)); // 计算全排列 List<List<Integer>> result = new ArrayList<>(); permutation(nums, 0, result); System.out.println("permutation result: " + result); } } ``` 输出结果为: ``` permutation: 60 combination: 10 permutation result: [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2]] ``` 其中,`permutation`和`combination`函数分别计算排列数和组合数,`permutation`函数使用阶乘实现,`combination`函数使用排列数实现。 `permutation`函数使用递归实现全排列,`swap`函数用于交换数组中两个元素的位置。在`main`函数中,我们使用`permutation`函数计算`[1, 2, 3]`的全排列,并将结果存储在`result`变量中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值