* Leetcode 93. Restore IP Addresses

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


简单dfs,结合具体ip的格式要求剪枝即可

class Solution {
public:
    vector restoreIpAddresses(string s) {
        vector ans;
        string prefix = "";
        dfs(s, 0, 0, prefix, ans);
        return ans;
    }
    
    bool legal(string s) {
        if ( s[0] == '0' && s.size() > 1 ) return false;
        
        return ( stoi(s) <=255 );
    }
    
    void dfs(string ip, int cur, int already_cnt, string prefix, vector &ans) {
        if (cur >= ip.size()) {
            return ;
        }

        for (int i = 0; i < 3; i++) {
            if (cur + i >= ip.size() )continue;
            string seg = ip.substr(cur, i+1);
            if (legal(seg)) {
                if (already_cnt == 3) {
                    string one_ans = prefix + seg;
                    if (one_ans.size() == ip.size() + 3)
                        ans.push_back(prefix + seg);
                } else {
                    dfs(ip, cur + i + 1, already_cnt + 1, prefix + seg + '.', ans);
                }
            }
        }
    }
    
};





你可能感兴趣的:(LeetCode题解,搜索-DFS)