LeetCode 93. 复原IP地址(Medium)

原题链接:https://leetcode-cn.com/problems/restore-ip-addresses/

题目描述

给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
有效的 IP 地址 正好由四个整数(每个整数位于 0 到 255 之间组成,且不能含有前导 0),整数之间用 ‘.’ 分隔。
例如:“0.1.2.201” 和 “192.168.1.1” 是 有效的 IP 地址,但是 “0.011.255.245”、“192.168.1.312” 和 “192.168@1.1” 是 无效的 IP 地址。
示例 1:
输入:s = “25525511135”
输出:[“255.255.11.135”,“255.255.111.35”]
示例 2:
输入:s = “0000”
输出:[“0.0.0.0”]
示例 3:
输入:s = “1111”
输出:[“1.1.1.1”]
示例 4:
输入:s = “010010”
输出:[“0.10.0.10”,“0.100.1.0”]

题解

搜索顺序:依次搜索每一个数,每个数有多种选择方案。

#include <iostream>
#include <string>
#include <algorithm>
#include <cstring>

vector<string> res;
vector<string> restoreIpAddresses(string s) 
{
   string path = "";
   dfs(s, 0, path, 0);
   return res;
}

void dfs(string s, int start, string path, int k)
{
   if(start == s.size())
   {
       if(k == 4){
           res.push_back(path.substr(1));
       }
       
       return;
   }
   
   if(k > 4) return;
   
   if(k == 3&& start < s.size() -3) return;
   
   if(s[start] == '0')
   {
       dfs(s, start + 1, path + ".0", k + 1);
   }
   
   else
   {
       for(int i = start, t = 0; i < s.size(); i++)
       {

           t = t * 10 + s[i] - '0';

           if(t < 256) dfs(s, i + 1, path + "." + to_string(t), k + 1);

           else break;


       }
   }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值