leetcode93 - Restore IP Addresses - medium

Given a string s containing only digits, return all possible valid IP addresses that can be obtained from s. You can return them in any order.

A valid IP address consists of exactly four integers, each integer is between 0 and 255, separated by single dots and cannot have leading zeros. For example, "0.1.2.201" and "192.168.1.1" are valid IP addresses and "0.011.255.245", "192.168.1.312" and "192.168@1.1" are invalid IP addresses. 

 

Example 1:

Input: s = "25525511135"
Output: ["255.255.11.135","255.255.111.35"]

Example 2:

Input: s = "0000"
Output: ["0.0.0.0"]

Example 3:

Input: s = "1111"
Output: ["1.1.1.1"]

Example 4:

Input: s = "010010"
Output: ["0.10.0.10","0.100.1.0"]

Example 5:

Input: s = "101023"
Output: ["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]

 

Constraints:

  • 0 <= s.length <= 3000
  • s consists of digits only.
递归:keep track 1)当前组好的一部分ip 2)s里还剩下(用pos表示可用起始点)3)组到第几个segement了,总共0-3 4)结果
组好一个ip的最终条件是,现在已经到segent4了说明0-3都好了,并且pos也到s.size()了,说明s里的刚好用完了。
pruning:每个segment要求是[0,255],那对于当前组好的一部分ip,s里剩余的数量(s.size()-pos),至多是剩下未完成segment的3倍(后面每个segment3位),至少也得有剩余segment个(后面每个segment1位)。
每次从pos位开始,往后取1-3位,比如123,取1,12,123都可以再call dfs。用一个num来记录这个取到的这个数。
corner case:不能有leading zero,先call下一个level的dfs,再break。
细节:
1. dfs里的loop咋老把i写成pos,好几次了,debug还找半天,必须记下来。
2. 组ip的时候用ip+=s[i]+'.'就变字符了,大概是'.'和'a'这种作用差不多,这个'.'去dfs的param里再修改。
 
实现:至多3*3*3个combination,所以才能用exhausive search呀。
class Solution {
public:
    void dfs(string s, vector<string>& res, string ip, int pos, int segment){
        if (segment == 4 && pos==s.size()){
            ip.erase(ip.end()-1);
            res.push_back(ip);
            return;
        }
        if (s.size()-pos < (4-segment)) return;
        if (s.size()-pos > 3*(4-segment)) return;
        int num = 0;
        for (int i=pos; i<pos+3; i++){
            num = num*10 + (s[i]-'0');
            if (num <= 255){
                ip+=s[i];
                dfs(s, res, ip+'.',i+1, segment+1);
            }
        }
    }
    
    vector<string> restoreIpAddresses(string s) {
        vector<string> res;
        dfs(s, res, "", 0, 0);
        return res;
    }
};

 

posted @ 2020-11-02 08:51  little_veggie  阅读(107)  评论(0)    收藏  举报