C# dfs accepted


  • 0
    S
    public class Solution {
    public IList<string> RestoreIpAddresses(string s) {
        IList<string> result = new List<string>();
        
        bt("",result,s,0,3);
        return result;
    }
    
    public void bt(string str,IList<string> result,string s,int pos,int dot){
        if(dot==0){
            if(s.Length-pos>3||!isValid(s.Substring(pos)))return;
            str+=s.Substring(pos);
            result.Add(str);
        }
        
        for(int i=pos;i<s.Length&&i<=pos+2;i++){
            
            string add = s.Substring(pos,i-pos+1);
            if(isValid(add)){
                bt(str+add+".",result,s,i+1,dot-1);    
            }
        }
    }
    
    public bool isValid(string s){
        if(s.Length==0||(s!="0"&&s[0]=='0')||s.Length>3)return false;
        int num = Convert.ToInt32(s);
        if(0<=num&&num<=255)return true;
        return false;
    }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.