• Restore IP Addresses


    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)

    思路:递归,回溯

    c++代码:

    #include <iostream>
    #include <stdlib.h>
    #include <vector>
    #include <string>
    using namespace std;
    class Solution {
    public:
        vector<string> restoreIpAddresses(string s) {
            vector<string> v;
            string t = "";
            dfs(s, t, v, 1);
            return v;
        }
        void dfs(string s, string t, vector<string> &v, int count){
            if(count == 4){ 
                if(isValid(s)){
                    v.push_back(t+s);
                }
                return;    
            }
            int i;
            for(i = 1; i < 4; i++){
                if(i < s.size()){
                    string g = s.substr(0, i);
                    if(isValid(g)){
                        string m = s.substr(i);
                        dfs(m, t + g + ".", v, count + 1);
                    }
                }
            }
        }
        bool isValid(string g){
            int l = g.size();
            if(l > 3)return false;
            if( l >=2 && g[0] == '0')return false;
            int vv = atoi(g.c_str());
            return vv <= 255 && vv >= 0;
        }
    };
    
    int  main(){
        Solution *s = new Solution();
        vector<string> r = s->restoreIpAddresses("1111");
        vector<string>::iterator iter;
        for(iter = r.begin(); iter != r.end(); iter++){
            cout << *iter << endl;
        }
        delete s;
        return 1;
    }
    

      

      

  • 相关阅读:
    C++之Static与Const
    LInux主机与虚拟机网络链接
    C#数据类型与数据类型转化
    C#网编Console(二)
    C#网编Winform(三)
    C#网编基础类与API(一)
    C实现CPU大小端判断
    QT程序图标设置
    四、初识Socket套接字API
    C++之继承(二)
  • 原文地址:https://www.cnblogs.com/zhutianpeng/p/4272491.html
Copyright © 2020-2023  润新知