代码随想录算法训练营第二十八天| 78 子集 90 子集|| 93 复原IP地址

78 子集

由题意可知数组中的元素互不相同,所以在dfs中我们可以将当前的path直接加入到res中。

java 复制代码
class Solution {
    List<List<Integer>>res = new ArrayList<>();
    List<Integer>path = new LinkedList<>();
    public List<List<Integer>> subsets(int[] nums) {
        dfs(0,nums);
        return res;
    }
    private void dfs(int cnt,int[] nums){
        res.add(new LinkedList(path));
        for(int i = cnt;i < nums.length;i++){
            path.add(nums[i]);
            dfs(i + 1,nums);
            path.remove(path.size() - 1);
        }
    }
}

时间复杂度O(n×)

空间复杂度O(n)

90 子集||

java 复制代码
class Solution {
    List<List<Integer>>res = new ArrayList<>();
    List<Integer>path = new LinkedList<>();
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        dfs(0,nums);
        return res;
    }
    private void dfs(int cnt,int nums[]){
        res.add(new LinkedList(path));
        for(int i = cnt;i < nums.length;i++){
            if(i > cnt && nums[i] == nums[i - 1])continue;
            path.add(nums[i]);
            dfs(i + 1,nums);
            path.remove(path.size() - 1);
        }
    }
}

时间复杂度O(n×)

空间复杂度O(n)

93 复原IP地址

相关推荐
Andy7 分钟前
回文子串数目--动态规划算法
算法·动态规划
sin_hielo10 分钟前
leetcode 1930
算法·leetcode
塞北山巅13 分钟前
相机自动曝光(AE)核心算法——从参数调节到亮度标定
数码相机·算法
聆风吟º14 分钟前
【数据结构入门手札】算法核心概念与复杂度入门
数据结构·算法·复杂度·算法的特性·算法设计要求·事后统计方法·事前分析估算方法
vir021 小时前
密码脱落(最长回文子序列)
数据结构·c++·算法
福尔摩斯张1 小时前
二维数组详解:定义、初始化与实战
linux·开发语言·数据结构·c++·算法·排序算法
冰西瓜6001 小时前
模与内积(五)矩阵分析与应用 国科大
线性代数·算法·矩阵
努力学算法的蒟蒻2 小时前
day17(11.18)——leetcode面试经典150
算法·leetcode·面试
缘友一世2 小时前
模型微调DPO算法原理深入学习和理解
算法·模型微调·dpo
未若君雅裁2 小时前
斐波那契数列 - 动态规划实现 详解笔记
java·数据结构·笔记·算法·动态规划·代理模式