[LeetCode] Restore IP Addresses 回溯

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

For example:
Given "25525511135",

return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)

 

Hide Tags
  Backtracking String
   

   这题是一道回溯题,其实记录好断开的位置便容易处理了。我使用的便是递归搜索的方法,用一个数组记录了断开的位置。
#include <string>

#include <vector>

#include <iostream>

using namespace std;





class Solution {

public:

    vector<string> restoreIpAddresses(string s) {

        vector<string> ret;

        if(s.size()<4)  return ret;

        int idx[4] = {0,0,0,0};

        helpFun(ret,s,idx,1);

        return ret;

    }



    void helpFun(vector<string> &ret,string & s,int * idx, int id)

    {

        if(id==4){

//            for(int i =0;i<4;i++)

//                cout<<idx[i]<<" ";

//            cout<<endl;

            if(helpFun2(s.substr(idx[3])))

                ret.push_back(s.substr(idx[0],idx[1]-idx[0])+"."+

                              s.substr(idx[1],idx[2]-idx[1])+"."+

                              s.substr(idx[2],idx[3]-idx[2])+"."+

                              s.substr(idx[3]) );

            return ;

        }

        for(int i =idx[id-1]+1;i<s.length();i++){

            if(helpFun2(s.substr(idx[id-1],i-idx[id-1]))){

                idx[id] = i;

                helpFun(ret,s,idx,id+1);

            }

            else

                return ;

        }

    }



    bool helpFun2(string s)

    {

        if(s.length()==1&&s[0]=='0')    return true;

        if(s[0]=='0')   return false;

        int sum = 0;

        for(int i=0;i<s.length();i++){

            sum = sum* 10 + s[i]-'0';

            if(sum>255) return false;

        }

        return true;

    }

};



int main()

{

    string s="25525511135";

    Solution sol;

    vector<string> ret = sol.restoreIpAddresses(s);

    for(int i=0;i<ret.size();i++)

        cout<<ret[i]<<endl;

    return 0;

}

 

 
 
 

你可能感兴趣的:(LeetCode)