【LeetCode】78.子集

题目

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

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

示例 1:

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

示例 2:

输入:nums = [0]
输出:[[],[0]]

提示:

  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10
  • nums 中的所有元素 互不相同

解答

源代码

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> combine = new ArrayList<Integer>();

        dfs(res, combine, nums, 0);

        return res;
    }

    public void dfs(List<List<Integer>> res, List<Integer> combine, int[] nums, int index) {
            res.add(new ArrayList<Integer>(combine));

            if (index == nums.length) {
                return;
            }

        for (int i = index; i < nums.length; i++) {
            combine.add(nums[i]);
            dfs(res, combine, nums, i + 1);
            combine.remove(combine.size() - 1);
        }
    }
}

总结

经典的回溯算法,这道题要另外注意一下不能到索引结束再添加元素,要每次更新索引都需要添加元素。

猜你喜欢

转载自blog.csdn.net/qq_57438473/article/details/131946297