代码随想录算法训练营第二十八天| 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地址

相关推荐
qq_4335545411 小时前
C++数位DP
c++·算法·图论
AshinGau11 小时前
Softmax 与 交叉熵损失
神经网络·算法
似水এ᭄往昔11 小时前
【C++】--AVL树的认识和实现
开发语言·数据结构·c++·算法·stl
栀秋66611 小时前
“无重复字符的最长子串”:从O(n²)哈希优化到滑动窗口封神,再到DP降维打击!
前端·javascript·算法
xhxxx11 小时前
不用 Set,只用两个布尔值:如何用标志位将矩阵置零的空间复杂度压到 O(1)
javascript·算法·面试
有意义11 小时前
斐波那契数列:从递归到优化的完整指南
javascript·算法·面试
charlie11451419112 小时前
编写INI Parser 测试完整指南 - 从零开始
开发语言·c++·笔记·学习·算法·单元测试·测试
mmz120712 小时前
前缀和问题2(c++)
c++·算法
TL滕12 小时前
从0开始学算法——第十六天(双指针算法)
数据结构·笔记·学习·算法
蒲小英12 小时前
算法-贪心算法
算法·贪心算法