mgaw

导航

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

目录

78 子集

90 子集 ||

93 复原IP地址


78 子集

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

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×2^{n})

空间复杂度O(n)

90 子集 ||

将nums排序,去除同一树层中重复的组合。 

40 组合总和 || 47 全排列 ||思路相同。

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×2^{n})

空间复杂度O(n)

93 复原IP地址

class Solution {
    List<String>res = new ArrayList<>();
    List<String>path = new LinkedList<>();
    public List<String> restoreIpAddresses(String s) {
        if(s.length() < 4 || s.length() > 12)return res;
        dfs(s,0);
        return res;
    }
    private void dfs(String s,int cnt){
        if(path.size() == 4){
            String ans = String.join(".",path);
            if(ans.length() == s.length() + 3){//'.'的长度
                res.add(ans);
            }
            return;
        }
        for(int i = cnt;i < s.length() && i < cnt + 3;i++){
            String str = s.substring(cnt,i + 1);
            if(!is(str))break;//说明此时这段字符串不能作为path的一部分加入到res中
            path.add(str);
            dfs(s,i + 1);
            path.remove(path.size() - 1);
        }
    }
    private boolean is(String s){
        if(s.length() == 0 || s.length() > 3)return false;
        if(s.charAt(0) == '0' && s.length() > 1)return false;
        for(char ch : s.toCharArray()){
            if(!Character.isDigit(ch))return false;
        }
        if(Integer.parseInt(s) > 255)return false;
        return true;
    } 
}

posted on 2023-11-20 03:00  A魔法恐龙  阅读(9)  评论(0)    收藏  举报  来源