Loading

LeetCode 78 子集

LeetCode78 子集

题目描述

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

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

样例

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

算法分析

  • 枚举位置选择

时间复杂度

\(O(2^{n})\)

Java代码

class Solution {
    static List<List<Integer>> ans = new ArrayList<List<Integer>>();
    static List<Integer> t = new ArrayList<Integer>();

    static void dfs(int[] nums, int u){
        if(u == nums.length){
            ans.add(new ArrayList<Integer>(t));
            return;
        }

        t.add(nums[u]);
        dfs(nums,u+1);
        t.remove(t.size()-1);
        dfs(nums,u+1);
    }
    public List<List<Integer>> subsets(int[] nums) {
        ans.clear();
        dfs(nums,0);
        return ans;
    }
}
posted @ 2020-11-18 14:14  想用包子换论文  阅读(69)  评论(0)    收藏  举报