GuilinDev

Lc0078

05 August 2008

78 Subsets

原题概述

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
Input: nums = [1,2,3]
Output:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

题意和分析

同样一道回溯法的题目,解法和分析一模一样。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> results = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return results;
        }
        Arrays.sort(nums);
        backtracking(nums, results, new ArrayList<Integer>(), 0);
        return results;
    }
    private void backtracking(int[] nums, List<List<Integer>> results, List<Integer> oneResult, int index) {
        results.add(new ArrayList<>(oneResult)); // 把add放在这里,也可以放在循环里面,后者需要事先单独加上题目要求的一个空结果
        for (int i = index; i < nums.length; i++) {
            if (oneResult.contains(nums[i])) { //重复元素
                continue;
            }
            oneResult.add(nums[i]);
            backtracking(nums, results, oneResult, i + 1); // 注意这里是i + 1而不是index + 1
            oneResult.remove(oneResult.size() - 1);
        }
    }
}

结果添加在for循环之中,事先加好空的第一个结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> results = new ArrayList<>();
        List<Integer> oneResult = new ArrayList<>();
        Arrays.sort(nums); // 因为没有重复,不排序也会遍历所有组合,排序会有些小优化路径
        results.add(oneResult);
        dfs(nums, results, oneResult, 0);
        return results;
    }
    private void dfs(int[] nums, List<List<Integer>> results, List<Integer> oneResult, int index) {
        for (int i = index; i < nums.length; i++) {
            if (oneResult.contains(nums[i])) {
                continue;
            }
            oneResult.add(nums[i]);
            results.add(new ArrayList<>(oneResult));
            dfs(nums, results, oneResult, i + 1); // i + 1表示将当前元素的后面所有元素加上
            oneResult.remove(oneResult.size() - 1);
        }
    }
}