[LeetCode] 78. 子集 ☆☆☆(回溯)

描述

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

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

示例:

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

解析

和求字符串的全排序思路一样,回溯。只不过终结条件不一样。

代码

List<List<Integer>> list = new ArrayList<>();
    public List<List<Integer>> subsets(int[] nums) {
        if (null == nums || nums.length <= 0) {
            return list;
        }
        subsetsHelp(nums, new ArrayList<>(), 0);
        return list;
    }

    public void subsetsHelp(int[] nums, List<Integer> tempList, int startIndex) {
        if (startIndex <= nums.length) {
            list.add(new ArrayList<>(tempList));
        }
        for (int i = startIndex; i < nums.length; i++) {
            tempList.add(nums[i]);
            subsetsHelp(nums, tempList, i + 1);// 这里是i + 1,不是startIndex + 1。
            tempList.remove(tempList.size() - 1);
        }
    }

猜你喜欢

转载自www.cnblogs.com/fanguangdexiaoyuer/p/12074482.html