leetcode-数组-子集

一、题目描述

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

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

示例:

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

二、思路

三、代码实现

 1 package cn.zifuchuan;
 2 
 3 import java.util.LinkedList;
 4 import java.util.List;
 5 
 6 public class Test5 {
 7 
 8     public static void main(String[] args) {
 9         int[] nums = {1,2,3};
10         List<List<Integer>> list = subsets(nums);
11         System.out.println(list);
12     }
13     public static List<List<Integer>> subsets(int[] nums) {
14         List<List<Integer>> res = new LinkedList<>();
15         dfs(res, new LinkedList<Integer>(), nums, 0); //从含有0个元素的情况开始分析
16         return res;
17     }
18     
19     public static void dfs(List<List<Integer>> res, List<Integer> temp, int[] nums, int start) {
20         res.add(new LinkedList<Integer>(temp));
21         for (int i =start; i < nums.length; i++) {
22             temp.add(nums[i]);
23             dfs(res, temp, nums, i + 1);
24             temp.remove(temp.size() - 1);
25         }
26     }
27 }

 

posted @ 2019-03-20 13:24  夏末秋涼  阅读(399)  评论(0编辑  收藏  举报