代码随想录算法训练营Day25 | 93.复原IP地址 | 78.子集 | 90.子集II

今日任务

93.复原IP地址

  • 题目链接: https://leetcode.cn/problems/restore-ip-addresses/description/
  • 题目描述
    在这里插入图片描述

Code

class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        vector<string> ans;
        vector<string> path;
        int n = s.size();
        if(n > 12 || n < 4){
            return {};
        }
        function<void(int)> dfs = [&](int i)->void{
            if(i == n && path.size() == 4){
                ans.emplace_back(path[0] + "." + path[1] + "." + path[2] + "." + path[3]);
                return;
            }
            for(int j = i; j < n; j++){
                string t = s.substr(i, j - i + 1);
                if(t.size() > 3){
                    return;
                }
                int tNum = stoi(t);
                if(to_string(tNum) != t){
                    return;
                }
                if(path.size() < 4 && tNum >= 0 && tNum <= 255){
                    path.push_back(t);
                    dfs(j + 1);
                    path.pop_back();
                }
            }
        };
        dfs(0);
        return ans;
    }
};

78.子集

  • 题目链接: https://leetcode.cn/problems/subsets/description/
  • 题目描述
    在这里插入图片描述

Code

class Solution {
public:
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> ans;
        int n = nums.size();
        vector<int> path;
        function<void(int)> dfs = [&](int i)->void{
            ans.emplace_back(path);
            
            if(i == n){
                return;
            }
            // dfs(i + 1);

            // path.push_back(nums[i]);
            // dfs(i + 1);
            // path.pop_back();


            for(int j = i; j < n; j++){
                path.push_back(nums[j]);
                dfs(j + 1);
                path.pop_back();
            }
        };
        dfs(0);
        return ans;
    }
};

90.子集II

  • 题目链接:https://leetcode.cn/problems/subsets-ii/description/
  • 题目描述
    在这里插入图片描述

Code

class Solution {
public:
    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
        ranges::sort(nums);
        vector<vector<int>> ans;
        vector<int> path;
        int n = nums.size();

        function<void(int)> dfs = [&](int i)->void{
            ans.emplace_back(path);
            if(i == n){
                return;
            }

            for(int j = i; j < n; j++){
                if(j == i || j > i && nums[j] != nums[j - 1]){
                    path.push_back(nums[j]);
                    dfs(j + 1);
                    path.pop_back();
                }
            }
        };
        dfs(0);
        return ans;
    }
};
  • 15
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值