LeetCode 78. 子集

题目描述

🔥 78. 子集

思路分析

思路描述

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
func subsets(nums []int) [][]int {
	var res [][]int
	sort.Ints(nums)
	backtrack(nums, &res, []int{}, 0)
	return res
}

func backtrack(nums []int, res *[][]int, path []int, start int) {
	temp := make([]int, len(path))
	copy(temp, path)
	*res = append(*res, temp)

	for i := start; i < len(nums); i++ {
		path = append(path, nums[i])
		backtrack(nums, res, path, i+1)
		path = path[:len(path)-1]
	}
}

🍏 点击查看 Java 题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        backtrack(nums, new ArrayList<>(), res, 0);
        return res;
    }

    public void backtrack(int[] nums, List<Integer> path, List<List<Integer>> res, int start) {
        res.add(new ArrayList<>(path));
        for (int i = start; i < nums.length; i++) {
            if (i > start && nums[i] == nums[i - 1]) {
                continue;
            }
            path.add(nums[i]);
            backtrack(nums, path, res, i + 1);
            path.remove(path.size() - 1);
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        backtrack(nums, new ArrayList<>(), res, 0);
        return res;
    }

    public void backtrack(int[] nums, List<Integer> path, List<List<Integer>> res, int start) {
        res.add(new ArrayList<>(path));
        for (int i = start; i < nums.length; i++) {
            path.add(nums[i]);
            backtrack(nums, path, res, i + 1);
            path.remove(path.size() - 1);
        }
    }
}
本文作者:
本文链接: https://hgnulb.github.io/blog/2022/26448849
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!