120、【回溯算法】leetcode ——93. 复原 IP 地址(C++/Python版本)

题目描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
原题链接:93. 复原 IP 地址

解题思路

本题是分割问题,思路与131. 分割回文串(分割问题)类似,不同之处在于分割的判定条件分割方式

回溯三部曲:
(1)递归参数:

vector<string> res;
bool isValidIP(string s, int start, int end);
void backtracking(string s, int startIndex, int dotNum);

使用res存储结果。
isValidIPstartend为判定的IP位下标。
backtrackingstartIndex为下一次遍历起始下标,dotNum为记录已经点取的小数点个数。

(2)终止条件:

if(dotNum == 3) {
    // 判定是否为有效划分IP方式
    if(isValidIP(s, startIndex, s.size() - 1)) {            
        res.push_back(s);
    }
    return ;
}

点够三个点,若全部为有效IP,则加入结果集,否则跳过。

(3)单层搜索逻辑:

// 划分IP地址
for(int i = startIndex; i < s.size(); i++) {              
    if(isValidIP(s, startIndex, i)) {
        dotNum++;
        s.insert(s.begin() + i + 1, '.');           // 从i+1之前点上小数点
        backtracking(s, i + 2, dotNum);             // 已加入一个字符,一次从加2开始遍历
        s.erase(s.begin() + i + 1);                 // 移除点的小数点,进行回溯
        dotNum--;
    } else {
        break;                                      // 只要有一个不合法,直接跳出循环
    }
}

s中依次选取IP位来划分,使用isValidIP来判定划分的这段是否位有效IP。s.insert(x, '.')函数是在x之前插入’.',因此传入为i + 1。因为,s的长度增一,因此下次选择路径需从i + 2开始。回退时,再删除.

class Solution {
public:    
    vector<string> res;
    bool isValidIP(string s, int start, int end) {
        // 去除第三个小数点在最后的情况
        if(start >= s.size())                   return false;
        // 当为多位数时,若开头位0,则返回false
        if(start != end && s[start] == '0')     return false;
        // 当为三位数时(0为起始下标,所以差值为2),若大于255,则返回false
        if(end - start == 2) {
            int x = (s[start] - '0') * 100 + (s[start + 1] - '0') * 10 + (s[end] - '0');
            if(x > 255)         return false;
        // 超过三位数,直接返回false
        } else if(end - start > 2) {
            return false;
        }
        return true;
    }
    void backtracking(string s, int startIndex, int dotNum) {
        // 已点够三个小数点
        if(dotNum == 3) {
            // 判定是否为有效划分IP方式
            if(isValidIP(s, startIndex, s.size() - 1)) {            
                res.push_back(s);
            }
            return ;
        }
        // 划分IP地址
        for(int i = startIndex; i < s.size(); i++) {              
            if(isValidIP(s, startIndex, i)) {
                dotNum++;
                s.insert(s.begin() + i + 1, '.');           // 从i+1之前点上小数点
                backtracking(s, i + 2, dotNum);             // 已加入一个字符,一次从加2开始遍历
                s.erase(s.begin() + i + 1);                 // 移除点的小数点,进行回溯
                dotNum--;
            } else {
                break;                                      // 只要有一个不合法,直接跳出循环
            }
        }
    }
    vector<string> restoreIpAddresses(string s) {
        backtracking(s, 0, 0);        
        return res;
    }
};

Python

class Solution:
    def __init__(self):
        self.dot_num = 0
        self.res = []
    
    def isValidIP(self, s, start_index, end_index):
    	# 每次的start_index都是从目标待添加'.'的位置开始,因此为了防止'.'在最后的情况,需要找个判断
        if start_index > end_index:
            return False
        if start_index != end_index and s[start_index] == '0':
            return False
        num = 0
        if end_index - start_index == 2:
            for i in range(start_index, end_index + 1):
                if not s[i].isdigit():
                    return False
                num = num * 10 + int(s[i])
                if num > 255:
                    return False
        elif end_index - start_index > 2:
            return False
        
        return True		# 值位于0~255的数
	

    def backtracking(self, s, start_index):
        if self.dot_num == 3:
            if self.isValidIP(s, start_index, len(s) - 1):
				self.res.append(s)
            return
        
        for i in range(start_index, len(s)):
            if self.isValidIP(s, start_index, i):
                self.dot_num += 1
                self.backtracking(s[:i + 1] + '.' + s[i + 1:], i + 2)
                self.dot_num -= 1
            else:
                break


    def restoreIpAddresses(self, s: str) -> List[str]:
        self.backtracking(s, 0)
        return self.res


参考文章:93.复原IP地址

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

辰阳星宇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值