[LeetCode] 93. Restore IP Addresses

来源:互联网 发布:mac电脑excel内存不足 编辑:程序博客网 时间:2024/05/24 04:29

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) {        vector<string> res;        restoreIpAddresses(res, "", s, 0, 0);        return res;    }private:    void restoreIpAddresses(vector<string>& res, string comb, string& s, int nth, int level) {        int rest = (int)s.size() - nth, lower = (4 - level), upper = lower * 3;        if (rest > upper || rest < lower)            return;        if (level == 4 && nth == s.size()) {            res.push_back(comb);            return;        }        for (int i = nth; i < s.length() && i < nth + 3; i++) {            string str = s.substr(nth, i - nth + 1);            int val = stoi(str);            if (val >= 0 && val <= 255)                restoreIpAddresses(res, comb + (comb.length() > 0 ? string(".") + str : str), s, i + 1, level + 1);            if (s[nth] == '0') break;        }    }};

这里写图片描述这里写图片描述

原创粉丝点击