码迷,mamicode.com
首页 > 其他好文 > 详细

Restore IP Addresses

时间:2015-02-04 16:18:13      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

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;
}

  

  

Restore IP Addresses

标签:

原文地址:http://www.cnblogs.com/zhutianpeng/p/4272491.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!