[LeetCode] Restore IP Addresses

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 {
private:
    vector<string> res;
public:
    void dfs(int dep, int len, string s, string tmp)
    {
        if(len > s.size())  return;
        if(dep == 4)
        {
            if(len == s.size())
                res.push_back(tmp);
            return;
        }
        if(dep) tmp += '.';
        dfs(dep+1, len+1, s, tmp + s.substr(len, 1));
        if(s.substr(len, 2) >= "10" && s.substr(len, 2) <= "99")
            dfs(dep+1, len+2, s, tmp + s.substr(len, 2));
        if(s.substr(len, 3) >= "100" && s.substr(len, 3) <= "255")
            dfs(dep+1, len+3, s, tmp + s.substr(len, 3));
    }
    vector<string> restoreIpAddresses(string s) {
        res.clear();
        dfs(0, 0, s, "");
        return res;
    }
};


你可能感兴趣的:([LeetCode] Restore IP Addresses)