Restore IP Addresses

本文探讨了如何通过递归和回溯的方法解决给定字符串转换为所有可能的有效IP地址组合的问题,并提供了使用C++实现的示例代码。
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;
}

  

  

转载于:https://www.cnblogs.com/zhutianpeng/p/4272491.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值