LeetCode-93-Restore IP Addresses

Posted 无名路人甲

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-93-Restore IP Addresses相关的知识,希望对你有一定的参考价值。

算法描述:

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

Example:

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

解题思路:题目要求所有可能的结果,首先想到回溯法。重点有两个,字符串截取和IP地址合法性判断。

    vector<string> restoreIpAddresses(string s) {
        vector<string> results;
        backtracking(results,"", s, 0,0);
        return results;
    }
    
    void backtracking(vector<string>& results, string temp, string s, int index, int count){
        if(count > 4 ) return;
        if(count == 4 && index == s.size()){
            results.push_back(temp);
            return;
        }
        for(int i=1; i < 4; i++){
            if(index+i > s.size()) break;
            string res = s.substr(index,i);
            if((res[0]==0 && res.size() >1) || ( i==3 && stoi(res)>= 256)) continue;
            backtracking(results, temp+res + (count ==3 ? "" :"."), s, index+i, count+1);
        }
    }

 

以上是关于LeetCode-93-Restore IP Addresses的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 93. Restore IP Addresses

[leetcode]93. Restore IP Addresses还原IP地址

LeetCode-93-Restore IP Addresses

LeetCode93. Restore IP Addresses 面试题

leetcode 93-Restore IP Addresses(medium)

[LeetCode] 93. Restore IP Addresses