93. Restoring IP addresses

Title description:

insert image description here

Main idea:

At first I thought about using dfs bitwise recursion, but some conditions were always badly judged. Then I read the solution and found that each step can cycle 1-3 bits, so everything is easy to judge.

class Solution {
    
    
public:
    vector<string> ans;
    int n;
    void dfs(int index,int k,string nowans,string s)
    {
    
    
        if(k==4||index==n)
        {
    
    
            if(k==4&&index==n)
                ans.push_back(nowans);
            return;
        }
        for(int i=1;i<=3;++i)
        {
    
    
            if(index+i>n) continue;
            if(s[index]=='0'&&i!=1) continue;
            string nows = s.substr(index,i);
            if(i==3&&nows>"255") continue;
            if(k!=3)
                nows+='.';
            dfs(index+i,k+1,nowans+nows,s);
        }
    }
    vector<string> restoreIpAddresses(string s) {
    
    
        n=s.length();
        string nowans="";
        dfs(0,0,nowans,s);
        return ans;
    }
};

Guess you like

Origin blog.csdn.net/weixin_54385104/article/details/130402108