leetcode 78. 子集

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

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

示例:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subsets
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

基本思路:

  对于问题[1,2,3,4,5](假设为问题a)的解可由子问题[2,3,4,5](假设为问题b)的解来构建。问题a的解就是:元素1(问题a特有元素),元素1与问题b的解的组合。

 1 public class _78 {
 2 
 3     private List<List<Integer>> result(int[] nums, int i){
 4         if (i == nums.length-1){
 5             List<List<Integer>> res = new ArrayList<>();
 6             List<Integer> sub = new ArrayList<>();
 7             sub.add(nums[i]);
 8             res.add(sub);
 9             return res;
10         }
11         List<List<Integer>> r = result(nums, i + 1);
12 
13         List<List<Integer>> curR = new ArrayList<>(r);
14         // 加入当前位置解
15         List<Integer> sub = new ArrayList<>();
16         sub.add(nums[i]);
17         curR.add(sub); // 当前位置也是一个解
18 
19         // 将当前位置与其子问题的解进行合并
20         for (List<Integer> elem : r){
21             List<Integer> subElem = new ArrayList<>();
22             subElem.add(nums[i]);
23             subElem.addAll(elem);
24             curR.add(subElem);
25         }
26         return curR;
27     }
28 
29     public List<List<Integer>> subsets(int[] nums) {
30         List<List<Integer>> result = result(nums, 0);
31         List<List<Integer>> r = new ArrayList<>();
32         List<Integer> t = new ArrayList<>();
33         r.add(t);
34         r.addAll(result);
35         return r;
36     }
37 
38     public static void main(String[] args) {
39         List<List<Integer>> subsets = new _78().subsets(new int[]{1, 2, 3,4,5});
40         for (List<Integer> elem : subsets) {
41             System.out.println(elem.toString());
42         }
43     }
44 }
原文地址:https://www.cnblogs.com/yfs123456/p/11569522.html