1. 程式人生 > 實用技巧 >Leetcode 08.04 冪集 回溯與點陣圖

Leetcode 08.04 冪集 回溯與點陣圖

  比較常規的解法為回溯解法:

    List<List<Integer>> reList = new LinkedList<List<Integer>>();

    public final List<List<Integer>> subsets1(int[] nums) {
        reList.add(new ArrayList<Integer>());
        Stack<Integer> stack = new Stack<Integer>();
        
//所有可能長度 for (int i = 1; i <= nums.length; i++) { //所有可能頭元素 for (int j = 0; j <= nums.length - i; j++) { subWay(nums, j, i, stack); } } return reList; } /** * @Author Niuxy * @Date 2020/7/21 12:26 下午 * @Description 遍歷已 flag 為頭元素,長度為 length 的所有可能子序列
*/ private final void subWay(int[] nums, int flag, int length, Stack<Integer> stack) { if (length == 1) { if (flag < nums.length) { stack.push(nums[flag]); reList.add(new ArrayList<Integer>(stack)); stack.pop(); }
return; } if (length > nums.length - flag || flag > nums.length) { return; } stack.push(nums[flag]); for (int i = flag + 1; i < nums.length; i++) { subWay(nums, i, length - 1, stack); } stack.pop(); }

  除此之外還有一種取巧的方法:點陣圖。

  每個自然數都是獨一無二的,它們的二進位制表示形式也是。

  對於 n 個元素的輸入,將會有 二的 N 次方(設為 k )種排列組合方式。

  0 的二進位制表示為 00000000 000000000 00000000 00000000

  1 的二進位制表示為 00000000 000000000 00000000 00000001

  2 的二進位制表示為 00000000 00000000 00000000 00000010

  對於每個數的二進位制表示,對應到輸入的陣列下標,1 表示選擇該元素,0 表示不選擇該元素。

  則從 1 到 k 的點陣圖可以完全的表示所有可能的組合。

  點陣圖解法:

/**
     * @Author Niuxy
     * @Date 2020/7/21 12:31 下午
     * @Description 點陣圖解法
     */
    public final List<List<Integer>> subsets(int[] nums) {
        int source = (int) Math.pow(2, nums.length);
        List<List<Integer>> reList = new LinkedList<List<Integer>>();
        for (int i = 1; i <= source; i++) {
            List<Integer> inList = new LinkedList<Integer>();
            for (int j = 0; j < nums.length; j++) {
                if (((i >>> j) & 1) == 1) {
                    inList.add(nums[j]);
                }
            }
            reList.add(inList);
        }
        return reList;
    }

  點陣圖解法效果: