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)
基本思路:
ip分为4段,
每段合法的值,1位时,为任意; 2位时,第一位不能为0;3位时,第一位,不能超过3。。。。
用递归,每层判断一个段。并记录其范围。
由于最多4段,故递归,最多4层。
每层,最多3次偿试。
此代码在leetcode上实际执行时间为5ms。
class Solution { public: vector<string> restoreIpAddresses(string s) { vector<string> ans; vector<int> ip; helper(ans, ip, s, 0); return ans; } void helper(vector<string> &ans, vector<int> &ip, const string &s, int start) { if (ip.size() == 4 && ip[3] == s.size()) { ans.push_back(s.substr(0, ip[0])); for (int i=0; i<3; i++) { ans.back().append(1, '.'); ans.back().append(s, ip[i], ip[i+1]-ip[i]); } return; } if (ip.size() == 4 || start == s.size()) return; for (int i=1; i<=3; i++) { if (start + i > s.size()) break; if (i == 2 && s[start] == '0') continue; else if (i == 3 && (s[start] == '0' || s[start] > '2' || s[start] == '2' && (s[start+1] > '5' || s[start+1] == '5' && s[start+2] > '5'))) continue; ip.push_back(start+i); helper(ans, ip, s, start+i); ip.pop_back(); } } };
Restore IP Addresses -- leetcode
原文地址:http://blog.csdn.net/elton_xiao/article/details/45362529