• LeetCode: Restore IP Addresses


    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 }
    View Code
  • 相关阅读:
    oracle+st_geometry
    php开发面试题---php面向对象详解(对象的主要三个特性)
    php开发面试题---Mysql常用命令行大全
    php开发面试题---Linux常用命令大全
    php开发面试题---vue面试题(vue.js的好处及作用)
    php开发面试题---数据库SQL调优的几种方式
    剑指offer---2、二叉搜索树的后序遍历序列
    MYSQL中IN与EXISTS的区别
    mysql笔试题大餐---2、exists加一些查询
    正确理解MySQL中的where和having的区别
  • 原文地址:https://www.cnblogs.com/yingzhongwen/p/3031928.html
Copyright © 2020-2023  润新知