[leetcode]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:

Input: nums = [1,2,3]
Output:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

题目

求给定数组的所有子集

思路

DFS

代码

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

猜你喜欢

转载自www.cnblogs.com/liuliu5151/p/9828170.html