LeetCode·93. Restore IP Addresses

本文介绍了一个递归分治算法,用于将由纯数字组成的字符串恢复为所有可能的有效IP地址组合。通过实例演示了如何实现这一过程,并给出了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

93. Restore IP Addresses
Given a string containing only digits, restore it by returning all possible valid IP address combinations.

Example:

Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]

思路:

  1. 递归;
  2. 分治

代码:

class Solution {
public:
    void help(string &s, string path, int id, vector<string> &res, int n){
        if(n == 3){
            if(id >= s.length())return;
            if(s[id] == '0'){
                if(id == s.length()-1){
                    path += "0";
                    res.push_back(path);
                }
                return;
            }
            string tmp = s.substr(id, s.size());
            int num = stoi(tmp);
            if(num <= 255){
                path += tmp;
                res.push_back(path);
            }
            return;
        }else if(id >= s.length()){
            return;
        }else{
            string tmp_path;
            for(int i = id, k = 1; i < id+3 && id+k-1 < s.length(); ++i, ++k){
                string str = s.substr(id, k);
                if(str[0] == '0' && str.length() == 1){
                    tmp_path = path + str + ".";
                    help(s, tmp_path, i+1, res, n+1);
                }else if(str[0] == '0' && str.length() != 1){
                    break;
                }else if(str[0] != '0' && stoi(str) <= 255){
                    tmp_path = path + str + ".";
                    help(s, tmp_path, i+1, res, n+1);
                }
            }
        }
    }

    vector<string> restoreIpAddresses(string s) {
        vector<string> res;
        if(s.length() < 4 || s.length() > 12)return res;
        help(s, "", 0, res, 0);
        return res;
    }
};

结果:


这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值