leetcode-回溯法-字符串分割问题

文章介绍了两个C++编程题目,分别是将字符串分割成回文子串和将数字转换为包含特定字符范围的字符串表示。作者提供了Solution类的实现,展示了递归方法在解决这两个问题中的应用。
摘要由CSDN通过智能技术生成

131. 分割回文串

#include<vector>
#include<iostream>
#include<queue>
using namespace std;


class Solution {
public:
vector<string> path_;
vector<vector<string>> res_;
    vector<vector<string>> partition(string s) {
        bt(s, 0);
        return res_;
    }
    // 11:10
    void bt(const string& s, int start_idx) {
        if (start_idx >= s.size()) { 
            res_.push_back(path_);
            return; // 写不写return都可以,因为下面是bt(s,i+1),不会无限循环
        }
        for (int i = start_idx; i < s.size(); i++) {
            string sub_s = s.substr(start_idx, i - start_idx + 1);
            if (valid(sub_s)) {
                path_.push_back(sub_s);
                bt(s, i + 1); // bug, i+1又写成了start_idx!!好几道题都是这里出错的
                path_.pop_back();
            }
        }
    }

    bool valid(const string& str) {
        if (str.size() == 1) {
            return true;
        }
        int s = 0;
        int e = str.size() - 1;

        while(s < e) {
            if (str[s++] != str[e--]) {
                return false;
            }
        }
        return true;
    }
};

int main() {

    Solution s;
    auto res = s.partition("aab");
    for (auto vs : res) {
        for (auto s: vs) {
        std::cout<<s<<" ";
        }
        std::cout<<endl;
    }
}

剑指offer-46. 把数字翻译成字符串

#include <iostream>
#include <vector>
#include <string>
using namespace std;

class Solution {
public:
vector<string> path_;
vector<vector<string>> res_;

int f(int num) {
    string num_str = to_string(num);
    bt(num_str, 0);
    return res_.size();
}
void bt(const string& num_str, int start_idx){
    if (start_idx >= num_str.size()) {
        res_.push_back(path_);
        return;
    }

    for (int i = start_idx; i < num_str.size(); i++) {
        auto sub_str = num_str.substr(start_idx, i - start_idx + 1);
        if (sub_str.size() <=2 && stoi(sub_str) <=26 && stoi(sub_str) >=0) { // 只有这里的valid条件和上面的不一样,其他都一样。
            path_.push_back(sub_str);
            bt(num_str, i + 1);
            path_.pop_back();
        }
    }
}
};

int main() {
    Solution s;
    int a, b;
    while (cin >> a) { // 注意 while 处理多个 case
        cout << s.f(a) << endl;
    }
 
}
// 64 位输出请用 printf("%lld")
  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值