http://www.cnblogs.com/remlostime/archive/2012/11/14/2770072.html

 class Solution {
private:
vector<string> ret;
int pos[];
public:
bool check(string &s, int beg, int end)
{
string ip(s, beg, end - beg + );
if (ip.size() == )
return "" <= ip && ip <= "";
else if (ip.size() == )
return "" <= ip && ip <= "";
else if (ip.size() == )
return "" <= ip && ip <= "";
else
return false;
} void dfs(int dep, int maxDep, string &s, int start)
{
if (dep == maxDep)
{
if (start == s.size())
{
int beg = ;
string addr;
for(int i = ; i < maxDep; i++)
{
string ip(s, beg, pos[i] - beg + );
beg = pos[i] + ;
addr += i == ? ip : "." + ip;
}
ret.push_back(addr);
}
return;
} for(int i = start; i < s.size(); i++)
if (check(s, start, i))
{
pos[dep] = i;
dfs(dep + , maxDep, s, i + );
}
} vector<string> restoreIpAddresses(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ret.clear();
dfs(, , s, );
return ret;
}
};

http://yucoding.blogspot.com/2013/04/leetcode-question-83-restore-ip.html

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)

Analysis:
This problem can be viewed as a DP problem. There needed 3 dots to divide the string, and make sure the IP address is valid:  less than or equal to 255, greater or equal to 0, and note that, "0X" or "00X" is not valid.
For the DP, the length of each part is from 1 to 3. We use a vector<string> to store each part, and cut the string every time. Details see the code.

Note that "atoi" is for c-string, <string> need to convert to cstring by str.c_str();

Code(Updated 201309):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
public:
    bool valid(string s){
        if (s.size()==3 && (atoi(s.c_str())>255 || atoi(s.c_str())==0)){return false;}
        if (s.size()==3 && s[0]=='0'){return false;}
        if (s.size()==2 && atoi(s.c_str())==0){return false;}
        if (s.size()==2 && s[0]=='0'){return false;}
        return true;
    }
 
    void getRes(string s, string r, vector<string> &res, int k){
        if (k==0){
            if (s.empty()){res.push_back(r);}
            return;
        }else{
            for (int i=1;i<=3;i++){
                if (s.size()>=i && valid(s.substr(0,i))){
                    if (k==1){getRes(s.substr(i),r+s.substr(0,i),res,k-1);}
                    else{getRes(s.substr(i),r+s.substr(0,i)+".",res,k-1);}
                }
            }
        }
    }
 
    vector<string> restoreIpAddresses(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<string> res;
        getRes(s,"",res,4);
        return res;
    }
};

Code(old version):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution {
public:
 
    void dp(string s,vector<string> &cur ,vector<string> &res){              
        if (cur.size()==3){ // if there are 4 parts in the original string
            cur.push_back(s); //all 4 parts and check if valid
            bool r = true;
            for (int i=0;i<4;i++){
                if (atoi(cur[i].c_str())>255){  //check value
                    r = false;
                    break;
                }
                if ((cur[i].size()>1 && cur[i][0]=='0')){ //check "0X" "00X" and "0XX" cases
                    r =false;
                    break;
                }
            }       
            if (r){
                res.push_back(cur[0]+"."+cur[1]+"."+cur[2]+"."+cur[3]);
            }
            cur.pop_back();
             
        }else{
            for (int i=0;i<3;i++){
                if (s.size()>i+1){
                    cur.push_back(s.substr(0,i+1));
                    dp(s.substr(i+1,(s.size()-i-1)),cur,res);
                    cur.pop_back();
                }
            }
        }
         
    }
 
 
    vector<string> restoreIpAddresses(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<string> res,cur;
        if (s.size()>12 || s.size()<4 ){return res;}
        dp(s,cur,res); // cur stores the current separation
        return res;
    }
};

 

leetcode-Restore IP Addresses-ZZ的更多相关文章

  1. LeetCode: Restore IP Addresses 解题报告

    Restore IP Addresses My Submissions Question Solution Given a string containing only digits, restore ...

  2. [LeetCode] Restore IP Addresses 复原IP地址

    Given a string containing only digits, restore it by returning all possible valid IP address combina ...

  3. [leetcode]Restore IP Addresses @ Python

    原题地址:https://oj.leetcode.com/problems/restore-ip-addresses/ 题意: Given a string containing only digit ...

  4. LeetCode——Restore IP Addresses

    Given a string containing only digits, restore it by returning all possible valid IP address combina ...

  5. [LeetCode] Restore IP Addresses 回溯

    Given a string containing only digits, restore it by returning all possible valid IP address combina ...

  6. LeetCode Restore IP Addresses

    DFS class Solution { public: vector<string> restoreIpAddresses(string s) { return insertDot(s, ...

  7. leetcode 93. Restore IP Addresses(DFS, 模拟)

    题目链接 leetcode 93. Restore IP Addresses 题意 给定一段序列,判断可能组成ip数的所有可能集合 思路 可以采用模拟或者DFS的想法,把总的ip数分成四段,每段判断是 ...

  8. 【leetcode】Restore IP Addresses

    Restore IP Addresses Given a string containing only digits, restore it by returning all possible val ...

  9. 【LeetCode】93. Restore IP Addresses

    Restore IP Addresses Given a string containing only digits, restore it by returning all possible val ...

  10. LeetCode解题报告—— Reverse Linked List II & Restore IP Addresses & Unique Binary Search Trees II

    1. Reverse Linked List II Reverse a linked list from position m to n. Do it in-place and in one-pass ...

随机推荐

  1. erlang随笔3--OTP

    OTP最核心的概念就是行为.一个行为封装了某种常见的行为模式.可以把这些行为理解为某种应用程序框架.可以通过回调模块来 定制这些框架.OTP依靠行为引用了容错,扩容和动态代码升级等特性.所以在写回调模 ...

  2. 【Css】Layout布局(二)

    css定位(Positioning) 所谓定位,即允许你定义元素框相对于其正常位置应该出现的位置,或者相对于父元素.另一个元素甚至浏览器窗口本身的位置. css提供了三种基本的定位机制:普通流.浮动和 ...

  3. Android表格布局之设置边框

    Android表格布局本身没有边框,不过可以通过背景色的设置可以实现表格边框的显示. 首先可以设置TableRow的背景色,然后设置内容的背景色.根据它们的颜色差就出现了边框.只要微调Content与 ...

  4. MySQL备份和还原数据

    MySQL备份和还原数据 导出整个数据库 mysqldump -uroot -p database_name > db_backup.sql 导入整个数据库 mysql -uroot -p da ...

  5. 移动端手势事件 hammer.JS插件

                      一.引入hammer.JS 1.下载地址:http://download.csdn.net/detail/webxiaoma/9872249 2.官网地址:http ...

  6. 使用eclipse创建maven web项目

    1.新建项目: 2.选择模板: 3.输入项目信息: 4.新建的项目结构,发现index.jsp报错,直接删除重新创建一个index.jsp文件后,发现仍然报错,再在pom/xml文件中添加相应的ser ...

  7. [android] 网络链接类型和渠道

    1.实现方式 1.1使用HttpUrlConnection 1.2使用HttpClient 1.3使用Socket,比如:豌豆荚,聊天工具 2.通讯渠道 2.1 WLAN(wi-fi),100米左右的 ...

  8. 一:Redis安装

    redis在Linux上的安装 1)安装redis编译的c环境,yum install gcc-c++ 2)将redis-2.6.16.tar.gz上传到Linux系统中 3)解压到/usr/loca ...

  9. DataTables获取指定元素的行数据

    法1: 用jquey获取,var row = $('.edit').parent().parent(); 缺点:只能获取dom上的东西,不能获取没有渲染的数据 法2: 首先绑定行号到元素上 $('#e ...

  10. 《JavaWeb从入门到改行》那些年一起学习的Servlet

    目录 获取ServletContext : ServletContext接口中的一些方法 application域存取数据功能 代码演示: application域获取项目文件路径 代码演示: API ...