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

相关推荐
如竟没有火炬15 分钟前
全排列——交换的思想
开发语言·数据结构·python·算法·leetcode·深度优先
寂静山林28 分钟前
UVa 12526 Cellphone Typing
算法
kyle~1 小时前
C++---嵌套类型(Nested Types)封装与泛型的基石
开发语言·c++·算法
sali-tec2 小时前
C# 基于halcon的视觉工作流-章48-短路断路
开发语言·图像处理·人工智能·算法·计算机视觉
墨染点香2 小时前
LeetCode 刷题【128. 最长连续序列】
算法·leetcode·职场和发展
被AI抢饭碗的人2 小时前
算法题(240):最大食物链计数
算法
熬了夜的程序员2 小时前
【LeetCode】82. 删除排序链表中的重复元素 II
数据结构·算法·leetcode·链表·职场和发展·矩阵·深度优先
欧克小奥2 小时前
Floyd判圈算法(Floyd Cycle Detection Algorithm)
算法·floyd
熬了夜的程序员3 小时前
【LeetCode】83. 删除排序链表中的重复元素
算法·leetcode·链表
胖咕噜的稞达鸭4 小时前
AVL树手撕,超详细图文详解
c语言·开发语言·数据结构·c++·算法·visual studio