【LeetCode-Medium-Java】78. 子集

题目:

给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。

示例:

输入: nums = [1,2,3]
输出:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

解题思路:回溯算法

注意:

1、不用考虑去重

2、for循环中递归的时候,传入的是i+1,不是cur+1!!!

代码:

public static List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if (nums.length == 0)   return res;

        List<Integer> path = new ArrayList<>();
        int cur = 0;

        dfs(nums,path,res,cur);
        return res;
    }

    private static void dfs(int[] nums, List<Integer> path, List<List<Integer>> res, int cur) {
        res.add(new ArrayList<>(path));
        for (int i = cur; i <nums.length ; i++) {
            path.add(nums[i]);
            dfs(nums,path,res,i+1);
            path.remove(path.size()-1);
        }

    }

猜你喜欢

转载自blog.csdn.net/weixin_44284276/article/details/108689679