erase的时候没考虑到.加上去之后删除位置的变化,基本一次过,少数次过
1 class Solution { 2 public: 3 void dfs(vector<string> &ret, string tmp, string s, int dep, int maxsize, int beg) { 4 if (beg > maxsize) return; 5 if (dep == 4) { 6 if (beg == maxsize) { 7 tmp.erase(beg+3, 1); 8 ret.push_back(tmp); 9 } 10 return; 11 } 12 dfs(ret, tmp+s[beg]+'.',s, dep+1, maxsize, beg+1); 13 if (s.substr(beg, 2) >= "10" && s.substr(beg, 2) <= "99") 14 dfs(ret, tmp+s.substr(beg, 2)+'.', s, dep+1, maxsize, beg+2); 15 if (s.substr(beg, 3) >= "100" && s.substr(beg, 3) <= "255") 16 dfs(ret, tmp+s.substr(beg, 3)+'.', s, dep+1, maxsize, beg+3); 17 } 18 vector<string> restoreIpAddresses(string s) { 19 // Start typing your C/C++ solution below 20 // DO NOT write int main() function 21 vector<string> ret; 22 string tmp = ""; 23 dfs(ret, tmp, s, 0, s.size(), 0); 24 return ret; 25 } 26 };
C#
1 public class Solution { 2 public List<string> RestoreIpAddresses(string s) { 3 List<string> ans = new List<string>(); 4 string tmp = ""; 5 dfs(ref ans, tmp, s, 0, s.Length, 0); 6 return ans; 7 } 8 public void dfs(ref List<string> ans, string tmp, string s, int dep, int maxSize, int beg) { 9 if (beg > maxSize) return; 10 if (dep == 4) { 11 if (beg == maxSize) { 12 ans.Add(tmp.Substring(0, tmp.Length-1)); 13 } 14 return; 15 } 16 if (beg < maxSize) dfs(ref ans, tmp + s[beg] + '.', s, dep + 1, maxSize, beg + 1); 17 if (beg + 2 <= maxSize && string.Compare(s.Substring(beg, 2), "10") >= 0 && string.Compare(s.Substring(beg, 2), "99") <= 0) 18 dfs(ref ans, tmp + s.Substring(beg, 2) + '.', s, dep + 1, maxSize, beg + 2); 19 if (beg + 3 <= maxSize && string.Compare(s.Substring(beg, 3), "100") >= 0 && string.Compare(s.Substring(beg, 3), "255") <= 0) 20 dfs(ref ans, tmp + s.Substring(beg, 3) + '.', s, dep + 1, maxSize, beg + 3); 21 } 22 }