LeetCode_Restore IP Address

本文介绍了一种通过递归深度优先搜索(DFS)算法来恢复由纯数字字符串组成的可能的有效IP地址组合的方法。该方法首先检查输入字符串的有效性,然后通过DFS遍历所有可能的IP地址分割方式,并将有效组合加入到结果集中。

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

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

For example:
Given "25525511135",

return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)

class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<string> ans;
    	if (s == "" || s.length() > 12)
    	{
    		return ans;
    	}
    	string vS[4];
    	RestoreIPDFS(ans, vS, 0, s, 0);
    	return ans;
    }
    
        
    void RestoreIPDFS(vector<string> &ans, string vS[], int count, string &s, int step)
    {
        if (count == 4)
    	{
    		if (step == s.length())
    		{
    			string str = vS[0];
    			for (int i = 1; i < 4; ++i)
    			{
    				str += '.';
    				str += vS[i];
    			}
    			ans.push_back(str);
    		}
    		return;
    	}
    	// 如果当前s中剩余的长度为[4-count, 3*(4-count)]则可以
    	int remain = s.length() - step;
    	if ((remain >= (4 - count)) && (remain <= (12 - 3 * count)))
    	{// 此次解析i个字符
    		for (int i = 1; i <= min(3, remain); ++i)
    		{
    			string tmp = s.substr(step, i);
    			// 如果长度不为0,则第一个不能为0
    			if (i > 1 && tmp[0] == '0')
    			{
    				continue;
    			}
    			if (atoi(tmp.c_str()) <= 255)
    			{
    				vS[count] = tmp;
    				RestoreIPDFS(ans, vS, count + 1, s, step + i);
    			}
    		}
    	}
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值