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;
            }
    };
  • 相关阅读:
    运维岗春招--part2
    python 题库|刷题
    leetcode刷题
    运维面经汇总
    python自动化运维阅读笔记
    Python编程汇总
    old_boy 运维学习-第一期
    团队博客作业-Week3
    个人对final发布产品的排名
    各组对final发布产品的排名
  • 原文地址:https://www.cnblogs.com/diegodu/p/4383721.html
Copyright © 2011-2022 走看看