zoukankan      html  css  js  c++  java
  • [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)

    Hide Tags
     Backtracking String
     

    思路:dfs,backtrace,ip只能由3位数字组成,1、2、3位逐一尝试, 2位的时候第一位不能为0,3位是0~255

    class Solution {
        vector<string> m_res;
        vector<string> m_str;
        public:
            void dfs(int dep, string s)
            {
                //printVector(m_str);
                if(m_str.size() > 4)
                    return;
                if(m_str.size() == 4 && dep < s.size())
                    return;
    
                if(dep == s.size())
                {
                    if(m_str.size() == 4)
                    {
                        string tmpStr;
                        for(int i = 0; i < 3; i++)
                        {
                            tmpStr += (m_str[i] + ".");
                        }
                        tmpStr += m_str[3];
                        m_res.push_back(tmpStr);
                    }
                    return;
                }
    
                for(int i = 1; i <= 3; i++)
                {
                    if((dep+i-1) >= s.size())
                        break;
                    if(i == 2)
                    {
                        if(s[dep] == '0')
                            break;
                    }
                    else if(i == 3)
                    {
                        if(s[dep] == '1' ||
                                (s[dep] == '2' && (s[dep+1] <= '4' || (s[dep+1] == '5' && s[dep+2] < '6'))))
                            ;
                        else
                            break;
                    }
                    m_str.push_back(s.substr(dep, i));
                    dfs(dep + i, s);
                    m_str.pop_back();
                }
    
    
            }
            vector<string> restoreIpAddresses(string s)
            {
                m_res.clear();
                m_str.clear();
                dfs(0, s);
                return m_res;
            }
    };
  • 相关阅读:
    Linux下安装MySql8
    root与alias主要区别
    TCP/UDP 常用端口列表
    kafka文档
    kafka监测工具(可视化)
    Kafka消息队列
    postgresql
    gulp babel 配置不报错也没有输出结果的原因
    gulp中常用的模块
    判断浏览器标签页是隐藏或者显示状态
  • 原文地址:https://www.cnblogs.com/diegodu/p/4383721.html
Copyright © 2011-2022 走看看