[leetCode]78. 子集

[leetCode]78. 子集
16/100
保存草稿
发布文章
renweiyi1487
未选择任何文件

题目

链接:https://leetcode-cn.com/problems/subsets

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

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

示例:

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

回溯

回溯法可以将该问题抽象成一棵树,与其他问题(只需添加叶子节点不同)该题需要添加树上的所有节点
在这里插入图片描述

class Solution {

    private List<List<Integer>> result = new ArrayList<>();

    private List<Integer> path = new ArrayList<>();

    public List<List<Integer>> subsets(int[] nums) {
        backTracking(nums, 0);
        return result;
    }

    private void backTracking(int[] nums, int startIndex) {
        // 收集子集
        result.add(new ArrayList<>(path));
        if (startIndex == nums.length) {
            return;
        }
        for (int i = startIndex; i < nums.length; i++) {
            path.add(nums[i]);
            
            backTracking(nums, i + 1);
            path.remove(path.size() - 1);
        }
    }
}

题目
链接:https://leetcode-cn.com/problems/subsets

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

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

示例:

输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
回溯
回溯法可以将该问题抽象成一棵树,与其他问题(只需添加叶子节点不同)该题需要添加树上的所有节点
在这里插入图片描述

class Solution {

private List<List<Integer>> result = new ArrayList<>();

private List<Integer> path = new ArrayList<>();

public List<List<Integer>> subsets(int[] nums) {
    backTracking(nums, 0);
    return result;
}

private void backTracking(int[] nums, int startIndex) {
    // 收集子集
    result.add(new ArrayList<>(path));
    if (startIndex == nums.length) {
        return;
    }
    for (int i = startIndex; i < nums.length; i++) {
        path.add(nums[i]);
        
        backTracking(nums, i + 1);
        path.remove(path.size() - 1);
    }
}

}
Markdown 869 字数 56 行数 当前行 55, 当前列 0 文章已保存19:17:23HTML 627 字数 39 段落

posted @ 2020-11-06 19:18  消灭猕猴桃  阅读(90)  评论(0编辑  收藏  举报