4

LeetCode-078-子集

 2 years ago
source link: https://segmentfault.com/a/1190000040914082
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

LeetCode-078-子集

发布于 11 月 5 日

题目描述:给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。

解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl...
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:dfs(深度优先遍历)

声明2个全局变量分别为结果集(result)和当前路径(path),添加一个深度优先遍历的方法,该方法具体逻辑如下:

  • k=0时,即当前路径已经有k个数了,说明当前路径符合条件,添加到结果集中;
  • 然后遍历从1开始的数,递归调用dfs方法,调用完之后将当前路径的最后一个数从路径中去掉。

上面的处理过程和 LeetCode-077-组合 的逻辑完全一样,区别就是本题需要遍历所有可能的元素个数(0到n之间)的组合,然后都加到结果集中。

import java.util.ArrayList;
import java.util.List;

public class LeetCode_078 {
    /**
     * 结果集
     */
    private static List<List<Integer>> result = new ArrayList<>();
    /**
     * 当前路径
     */
    private static List<Integer> path = new ArrayList<>();

    /**
     * 多重调用dfs(深度优先遍历)
     *
     * @param nums
     * @return
     */
    public static List<List<Integer>> subsets(int[] nums) {
        result.add(new ArrayList<>());
        for (int i = 1; i <= nums.length; i++) {
            path = new ArrayList<>();
            dfs(0, nums, i);
        }
        return result;
    }

    /**
     * 深度优先遍历
     *
     * @param index 路径的起始位置
     * @param nums  原始的数组
     * @param k     路径剩下还需要几个值
     */
    private static void dfs(int index, int[] nums, int k) {
        if (k == 0) {
            /**
             * 当前已经有k个值,加到结果集中
             */
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = index; i < nums.length; i++) {
            path.add(nums[i]);
            dfs(i + 1, nums, k - 1);
            /**
             * 将当前路径的最后一个值去掉,然后继续遍历
             */
            path.remove(path.size() - 1);
        }
    }

    public static void main(String[] args) {
        int[] nums = new int[]{1, 2, 3};
        for (List<Integer> integers : subsets(nums)) {
            for (Integer integer : integers) {
                System.out.print(integer + " ");
            }
            System.out.println();
        }
    }
}

【每日寄语】 “坐而言,不如起而行”,在没有做出成绩时,就去学去做,把实力积攒起来等待机会。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK