leetcode93 复原IP地址 回溯

  • leetcode93 复原IP地址

  • https://leetcode.cn/problems/restore-ip-addresses/

  • 回溯其实就是横向遍历,纵向递归的组合。

  • for循环是横向遍历,遍历同一层,for循环内的回溯是纵向遍历

  • 不要忘记pop_back()以维护状态空间

python

'''

Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, OCaml, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.

'''
from typing import List


class Solution:
    def restoreIpAddresses(self, s: str) -> List[str]:
        size = len(s)
        if size < 4 or size > 12:
            return []

        path = []
        res = []
        self.__dfs(s, size, 0, 0, path, res)
        return res

    def __dfs(self, s, size, split_times, begin, path, res):
        if begin == size:
            if split_times == 4:
                res.append('.'.join(path))
            return

        if size - begin < (4 - split_times) or size - begin > 3 * (4 - split_times):
            return

        for i in range(3):
            if begin + i >= size:
                break

            ip_segment = self.__judge_if_ip_segment(s, begin, begin + i)

            if ip_segment != -1:
                path.append(str(ip_segment))
                self.__dfs(s, size, split_times + 1, begin + i + 1, path, res)
                path.pop()

    def __judge_if_ip_segment(self, s, left, right):
        size = right - left + 1

        if size > 1 and s[left] == '0':
            return -1

        res = int(s[left:right + 1])

        if res > 255:
            return - 1
        return res

mysolo = Solution()
res = mysolo.restoreIpAddresses("25525511135")
print(res)

作者:liweiwei1419
链接:https://leetcode.cn/problems/restore-ip-addresses/solution/hui-su-suan-fa-hua-tu-fen-xi-jian-zhi-tiao-jian-by/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

C++

  • 使用 int ip = stoi(s);转换数值
#include 
#include 
#include 
#include
using namespace std;


class Solution
{
private:
    vector<string> result;
public:
    vector<string> restoreIpAddresses(string s)
    {
        vector<string> path;
        
        if(s.size()<4||s.size()>16)//如果string是非法的ip字符串则直接返回即可
            return result;

        dfs(s, 0, path);
        return result;
    }
    bool __judge_if_ip_segment(string s) //判断是否是一个合法的IP范围
    {
        if(s[0]=='0'&&s.size()>=2)  //不能有前置0
            return false;
        cout<<s<<endl;
        int ip = stoi(s);//stoi函数. 作用是将 n 进制的字符串转化为十进制
        if(ip>255) //不能超出范围
            return false;
        return true;
    }
    //pos表示当前的起始位置,path表示当前已存路径
    void dfs(string &s,int pos,vector<string> &path)
    {
        if(path.size()==4)
        {
            if(pos==s.size()){//满足条件,存储结果
                string s = "";
                for (int i = 0; i < 3;i++)
                    s = s + path[i] + '.';
                s += path[3];
                result.push_back(s);
                return;
            }else{
                // //如果没有遍历至结尾说明该部分是无效的
                // if(path.size()==4&&pos<s.size())
                // if(path.size()==4&&pos>s.size())
                return;
            }
        }

       
        for (int i = 0; i <= 2;i++)
        {
            if(pos<s.size()){//如果前两个就用完了所有数据,那么就停止
                string ip = s.substr(pos, i + 1); //截取
                if(!__judge_if_ip_segment(ip)) 
                    break; 
                path.push_back(ip);
                dfs(s, pos+i + 1, path);
                path.pop_back();
            }
        }
    }
};


int main()
{
    unique_ptr<Solution> mysolo = unique_ptr<Solution>(new Solution());
    cout<<"Hello World"<<endl;
    string s = "101023"; //"0000";// "25525511135"; //
    vector<string> res = mysolo->restoreIpAddresses(s);
    for(auto v: res){
        cout<<v<<"-->";
    }
    return 0;
}

cg

  • stoi string to int

  • int num = 123456789;
    string s = to_string(num);

你可能感兴趣的:(笔记,tcp/ip,网络协议,网络)