美文网首页
0078. 子集

0078. 子集

作者: 蓝笔头 | 来源:发表于2021-09-02 20:05 被阅读0次

    题目地址

    https://leetcode-cn.com/problems/subsets/

    题目描述

    给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
    
    说明:解集不能包含重复的子集。
    
    示例:
    
    输入: nums = [1,2,3]
    输出:
    [
      [3],
      [1],
      [2],
      [1,2,3],
      [1,3],
      [2,3],
      [1,2],
      []
    ]
    

    题解

    回溯算法

    class Solution {
        public List<List<Integer>> subsets(int[] nums) {
            List<List<Integer>> results = new ArrayList<>();
           
            dfs(results, new ArrayList<>(), nums, 0);
            
            return results;
        }
    
        public void dfs(List<List<Integer>> results, List<Integer> result, int[] nums, int index) {
            // 添加到结果集
            results.add(new ArrayList<>(result));
    
            for (int i = index; i < nums.length; ++ i) {
                // 做选择
                result.add(nums[i]);
    
                dfs(results, result, nums, i + 1);
    
                // 撤销选择
                result.remove(result.size() - 1);
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:0078. 子集

          本文链接:https://www.haomeiwen.com/subject/ewpcwltx.html