day 27回溯 分割问题

文章介绍了如何利用深度优先搜索(DFS)算法解决两个字符串处理问题:131.分割回文串,93.复原IP地址。在分割回文串问题中,通过DFS遍历所有可能的子串并判断是否为回文;在复原IP地址问题中,同样使用DFS寻找所有可能的有效IP地址组合。
摘要由CSDN通过智能技术生成

回溯 分割问题框架

  void dfs(string s, int start){
        if(start >= s.size() && 中止条件){
            result.push_back(path);
            return;
        }
        for(int i=start; i<s.size(); i++){
            string ss = s.substr(start, i-start+1);   //切割字符串
            if(judge(ss)){    
                path.push_back(ss);
                dfs(s, i+1);
                path.pop_back();
            }
        }
    }

131. 分割回文串

  1. 分割问题与组合相同点 顺序拿, 不同在于组合可以不选。
  2. 当前字符串不是回文时不能break ef不是回文 efe是回文
  3. 截取字符串 s.substr(int start, int len)
class Solution {
public:
    vector<vector<string>>result;
    vector<string>path;
    vector<vector<string>> partition(string s) {
        dfs(s, 0);
        return result;
    }
    bool judge(string s){
        int start = 0;
        int end = s.size()-1;
        while(start <= end){
            if(s[start++] != s[end--])  return false;
        }
        return true;


    }
    void dfs(string s, int start){
        if(start >= s.size()){
            result.push_back(path);
            return;
        }
        for(int i=start; i<s.size(); i++){
            string cur = s.substr(start, i-start+1);
            if(!judge(cur)) continue;
            path.push_back(cur);
            dfs(s, i+1);
            path.pop_back();
        }

    }
};

93. 复原 IP 地址

class Solution {
public:
    vector<string>result;
    string path;
    int cnt = 0;
    vector<string> restoreIpAddresses(string s) {
        dfs(s, 0);
        return result;
    }
    bool judge(string s){
        if(s.size()>1 && s[0] == '0') return false;
        if(s.size()>3 ) return false;
        if(s.size() == 3 &&(s[0]>='3' ||(s[0]=='2' &&(s[1]>='6' || (s[1]=='5' && s[2]>='6'))))) return false;
        return true;
    }
    void dfs(string s, int start){
       
        if(start >= s.size() && cnt == 4){
            result.push_back(path);
            return;
        }
        if(cnt>=4 ||start >= s.size() ) return;
        for(int i=start; i<s.size(); i++){
            string cur = s.substr(start, i-start+1);
         
            if(judge(cur)){
        
                string temp = path;
                if(cnt<3) path = path + cur +".";
                else path = path + cur;
                cnt++;
                dfs(s, i+1);
                path = temp;
                cnt--;
            }
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值