Leetcode 93 Restore IP address

题意

给定一个字符串划分成4个子串,每个子串我都要满足0<= x <= 255,并且不能出现 x = “01”(不能以0开头的串)返回所有满足条件的组合
e.g. s = "25525511135"
out = ["255.255.11.135","255.255.111.35"]

题目链接

https://leetcode.com/problems/restore-ip-addresses/description/

思路

dfs遍历整个字符串。
退出条件如果切分的数量 >4退出dfs。如果切分数量为4并且所有所有的4个子串都满足0 <= x <= 255,加入答案,也要退出dfs。
dfs中还要保存当前遍历的起始位置,每一层dfs需要截取起始位置1位,2位,3位,判断截取的字符串,0 <= x <=255并且不能存在0开头的情况(除了0),如果截取的字符串满足条件,进入下一层dfs。

注意

由于我判断结束的条件是字符串的最后一位的下一位,index + i <= s.size() 所以我需要for循环的遍历中小于等于字符串的长度,不然会导致问题。

class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        vector<string> ret;
        string temp;
        dfs(0, 0, s, temp, ret);
        return ret;
    }

    void dfs(int index, int cnt, string& s, string& temp, vector<string>& ret) {
        if (cnt > 4) {
            return;
        }
        if(index == s.size()) {
            if (cnt == 4) {
                     //delete the dot
                temp = temp.substr(0, temp.size()-1);
                ret.push_back(temp);

            }
            return;
        }
        for(int i = 1; i <= 3 && index + i <= s.size(); i++) {
            string newStr = s.substr(index,i);
            if (newStr[0] == '0' && newStr.size() > 1) {
                break;
            }
            if (stoi(newStr) <= 255) {
                string cur = temp;
                temp += newStr;
                temp += ".";
                dfs(index + i, cnt + 1, s, temp, ret);
                temp = cur;
            }
        }
    }
};

时间复杂度: O ( 3 4 ) O(3^4) O(34) 最多有4层,每一层最多有3个分叉。常数时间
空间复杂度: O ( 16 ) O(16) O(16) 常数空间

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值