java数组排列组合_java算法题--递归求数组中数字排列组合问题

java算法题–递归求数组中数字排列组合问题

题目:有一个数组{1,2,3},输出数组中数字的所有可能组合;

比如:123、132、213…

解题思路

通过递归不停的交换数组中的两个数(当然,肯定是有规律的交换)

大概过程如下图:

2fcabaab1eb096097956ced0601fbd76.png

代码如下:

/*

* 题目:一个数组{1,2,3},输出数组中数字的所有排列情况

* 思路:递归交换两个数

* k=0 依次交换 0,0 0,1 0,2 得到 123 213 321

* 上次得到的数再递归调用函数:

* k=1 123交换得到 123 132

* 213交换得到 213 231

* 321交换得到 321 312

*/

public class Exercise1 {

private static int count = 0;

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

int[] arr = {1, 2, 3};

solution(arr, 0);

System.out.println("count: " + count);

}

/*

* 递归调用函数交换数组中的数

*/

public static void solution(int[] arr, int k) {

int n = arr.length;

if (k == n) {

for (int i : arr) {

System.out.print(i);

}

count++;

System.out.println();

}

for (int i = k; i < n; i++) {

swap(arr, k, i);

solution(arr, k + 1);

swap(arr, k, i);

}

}

/*

* 交换数组中两个数

*/

public static void swap(int[] arr, int x, int y) {

if (x != y) {

int temp = arr[x];

arr[x] = arr[y];

arr[y] = temp;

}

}

}

运行结果

123

132

213

231

321

312

count: 6

fcc3e5d3a727cb7c170d40acd40a44f3.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现n个数组排列组合,可以使用递归算法。 首先,我们定义一个函数,输入参数为n个数组一个空的结果列表。函数的作用是将n个数组进行排列组合,并将所有组合的结果保存在结果列表中。 然后,在函数中,我们使用两个循环嵌套来对数组进行排列组合。外层循环用于遍历数组的第一个元素,内层循环用于遍历其余n-1个数组的所有可能组合。 在内层循环中,我们将当前数组的第一个元素与剩余n-1个数组的所有可能组合拼接成新的组合,并递归调用函数。递归调用的参数为剩余的n-1个数组和拼接后的结果列表。 当递归调用的参数数组为空时,表示已经排列组合完成,将结果列表保存到最终的结果集中。 最后,返回最终的结果集。 下面是一个具体实现的示例代码: ```java import java.util.ArrayList; import java.util.List; public class PermutationCombination { public static void main(String[] args) { int[][] arrays = {{1, 2, 3}, {4, 5}, {6, 7, 8}}; List<List<Integer>> result = new ArrayList<>(); permutationCombination(arrays, new ArrayList<>(), result); System.out.println(result); } private static void permutationCombination(int[][] arrays, List<Integer> current, List<List<Integer>> result) { if (arrays.length == 0) { result.add(new ArrayList<>(current)); return; } for (int i = 0; i < arrays[0].length; i++) { current.add(arrays[0][i]); int[][] remaining = new int[arrays.length - 1][]; for (int j = 1; j < arrays.length; j++) { remaining[j - 1] = arrays[j]; } permutationCombination(remaining, current, result); current.remove(current.size() - 1); } } } ``` 运行上述代码,输出结果为: [[1, 4, 6], [1, 4, 7], [1, 4, 8], [1, 5, 6], [1, 5, 7], [1, 5, 8], [2, 4, 6], [2, 4, 7], [2, 4, 8], [2, 5, 6], [2, 5, 7], [2, 5, 8], [3, 4, 6], [3, 4, 7], [3, 4, 8], [3, 5, 6], [3, 5, 7], [3, 5, 8]] 以上代码实现了将3个数组进行排列组合的功能,你可以根据需要修改输入数组的个数来实现任意个数组排列组合

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值