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

作者站长头像
站长
· 阅读数 8

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]、
回复
1个回答
avatar
test
2024-07-02
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;
    }

}
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容