java[001,002,003]如何效率最高的穷举出两位以上的所有组合方式?

java 现有list1[11,33,22]
效率最高穷举出两位以上任意相连的方式,如:

[11,33]、[11,22]、[11,33,22]、[11,22,33]、

[33,22]、[33,11]、[33,11,22]、[33,22,11]、

[22,11]、[22,33]、[22,33,11]、[22,11,33]、


回答:

import java.util.*;

public class Test {

// 使用递归实现

public static void main(String[] args) {

int[] nums = { 11, 33, 22 };

for (int i = 2; i <= nums.length; i++) {

combine(nums, new int[i], 0, 0);

}

}

public static void combine(int[] nums, int[] temp, int start, int index) {

if (index == temp.length) {

permutation(temp, 0, temp.length - 1);

return;

}

for (int i = start; i < nums.length; i++) {

temp[index] = nums[i];

combine(nums, temp, i + 1, index + 1);

}

}

public static void permutation(int[] arr, int start, int end) {

if (start == end) {

System.out.println(Arrays.toString(arr));

} else {

for (int i = start; i <= end; i++) {

swap(arr, start, i);

permutation(arr, start + 1, end);

swap(arr, start, i);

}

}

}

public static void swap(int[] arr, int i, int j) {

int temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

}

}


回答:

跑一下吧:

import java.util.*;

public class Main {

public static void main(String[] args) {

List<Integer> list1 = Arrays.asList(11,33,22);

List<List<Integer>> res = enumerate(list1);

System.out.println(res);

}

private static List<List<Integer>> enumerate(List<Integer> list) {

List<List<Integer>> res = new ArrayList<>();

if (list.size() <= 1) {

return res;

}

for (int i = 0; i < list.size() - 1; i++) {

Integer num1 = list.get(i);

for (int j = i + 1; j < list.size(); j++) {

Integer num2 = list.get(j);

List<Integer> subList = list.subList(i, j + 1);

res.add(subList);

List<List<Integer>> subRes = enumerate(subList);

for (List<Integer> sub : subRes) {

res.add(sub);

}

}

}

return res;

}

}

以上是 java[001,002,003]如何效率最高的穷举出两位以上的所有组合方式? 的全部内容, 来源链接: utcz.com/p/945203.html

回到顶部