递归和动态规划解整数分解为字符串的问题

在这里插入图片描述

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

class int2strcount{
public:
    static int DO(int num){
        if(num < 10) return 1;
        cout << "DO: " << num << endl;
        int target = num %100;
        if(target >9 && target <26)
          return DO(num/10) + DO(num/100);
        return DO(num/10);
    }
    static int DO2(int num){
        unordered_map<int, int> cache;
        return dfs(num, cache);
    }
    static int DO3(int num){
        if(num < 10) return 1;
        int len= 1;
        for(int i =num; i>10; i/=10) len++;
        vector<int> dp(len+1, 1);
        for(int i =2; i<=len; i++){
            int temp = num; // 使用临时变量处理num的修改
            for (int j = 0; j < len - i; j++) {
                temp /= 10; // 跳过前面的位数
            }
            cout<< "dp: " << temp << endl;
            int target = temp % 100;
            // cout<< "target: " << target << endl;
            if(target >9 && target <26)
                dp[i] = dp[i-1] + dp[i-2];
            else
                dp[i] = dp[i-1];
        }
        return dp[len];
    }
private:
    static int dfs(int num, unordered_map<int, int>& cache){
        if(cache.find(num) != cache.end()) return cache[num];
        if(num < 10) return 1;
        cout << "dfs: " << num << endl;
        int target = num %100;
        if(target >9 && target <26){
            cache[num] = dfs(num/10, cache) + dfs(num/100, cache);
          return cache[num];
        }
        cache[num] = dfs(num/10, cache);
        return cache[num];
    }
};
int main(){
    int2strcount ic;
    cout<<ic.DO(1255258)<<endl;
    cout<<ic.DO2(1255258)<<endl;
    cout<<ic.DO3(1255258)<<endl;
    return 0;
}

DO和DO1是递归的解法,DO1是DO的剪枝。DO3是动态规划的解法。

DO: 1255258
DO: 125525
DO: 12552
DO: 1255
DO: 125
DO: 12
DO: 1255
DO: 125
DO: 12
dg: 6
dfs: 1255258
dfs: 125525
dfs: 12552
dfs: 1255
dfs: 125
dfs: 12
dg: 6
dp: 12
dp: 125
dp: 1255
dp: 12552
dp: 125525
dp: 1255258
dp: 6

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

石去皿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值