zoukankan      html  css  js  c++  java
  • LeetCode 78 子集

    LeetCode 78 子集

    问题描述
    给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
    说明:解集不能包含重复的子集。

    深度优先遍历 + 回溯

    执行用时:1 ms, 在所有 Java 提交中击败了99.39%的用户
    内存消耗:39 MB, 在所有 Java 提交中击败了61.47%的用户

    class Solution {
        private List<List<Integer>> results;
        //深度优先遍历DFS
        public List<List<Integer>> subsets(int[] nums) {
            //初始化结果集合
            results = new ArrayList<List<Integer>>();
            results.add(new ArrayList<Integer>());
            if(nums==null || nums.length==0) {
                return results;
            }
            dfs(nums, -1, new ArrayList<Integer>());
    
            return results;
        }
        
        public void dfs(int[] nums, int curr, List<Integer> result) {
            if(curr>=0 && curr<=nums.length-1) {
                results.add(new ArrayList<Integer>(result));
                if(curr==nums.length-1) {
                    return;
                }
            }
    
            //回溯
            for(int next=curr+1; next<nums.length; next++) {
                result.add(nums[next]);
                dfs(nums, next, result);
                result.remove(result.size()-1);
            }
        }
    }
    
  • 相关阅读:
    IP通信02
    h5网页 微信分享给好友,朋友圈-tp5
    微博常用链接
    Sublime Text3之安裝Emmet及使用技巧
    JS 写入到文件
    PHP之httpRequest
    图片上传预览
    滚动数字时钟
    旋转
    创建JavaScript标准对象--面试经常遇到的问题
  • 原文地址:https://www.cnblogs.com/CodeSPA/p/13700267.html
Copyright © 2011-2022 走看看