LeetCode(Restore IP Addresses)

深搜:

class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        vector<string> result;
        string path;
        dfs(s,result,path,0,0);
        return result;
    }
    void dfs(string &s,vector<string> &result,string path,int start,int step)
    {
        if(start==s.size()&&step==4)
        {
            path.pop_back();
            result.push_back(path);
            return;
        }
        if(s.size()-start<4-step||s.size()-start>(4-step)*3))return;
        int num=0;
        for(int i=start,i3;++i)
        {
            num=num*10+s[i]-'0';
            if(num<=255)
            {
                path.push_back(s[i]);
                dfs(s,result,path+'.',i+1,step+1);
                path.pop_back();
            }
            if(num==0)break;
        }
    }
};

你可能感兴趣的:(LeetCode(Restore IP Addresses))