[LeetCode]Decode Ways

class Solution {
//DFS here will be TLE
//So the intuitive is that this can be solved by DP
//get the maximum or minimum or number, we should give DP a shot for these kind of problems
//transform equation:
//if(IsCode(i)) f[i]+=f[i-1]
//if(IsCode(i-1, i)) f[i]+=f[i-2]
//initialize: f[0]=1, f[1]=IsCode(s[0])
public:
	bool IsCode(string s, int start, int end)
	{
		if(end-start+1 >= 3) return false;
		if(s[start] == '0') return false;
		int res = 0;
		for (int i = start; i <= end; ++i)
			res = res*10+s[i]-'0';
		if(res >= 1 && res <= 26)
			return true;
	}
	int numDecodings(string s) {
		// Start typing your C/C++ solution below
		// DO NOT write int main() function
		int n = s.size();
		if(n == 0) return 0;//note here
		vector<int> f(n+1, 0);
		f[0] = 1;
		if( IsCode(s, 0, 0) ) f[1] = 1;//when use constant subscript, always remember will it out of range?
		for (int i = 2; i <= n; ++i)
		{
			if( IsCode(s, i-1, i-1) ) f[i] += f[i-1];
			if( IsCode(s, i-1-1, i-1) ) f[i] += f[i-2];
		}
		return f[n];
	}
};

second time

class Solution {
public:
    int numDecodings(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(s.size() == 0) return 0;
        vector<int> f(s.size()+1, 0);
        f[0] = 1;
        if(s[0] != '0') f[1] = 1;
        for(int i = 2; i <= s.size(); ++i)
        {
            int curDigit = s[i-1]-'0';
            int prevDigit = s[i-2]-'0';
            int sum = prevDigit*10+curDigit;
            if(sum >= 10 && sum <= 26) f[i] += f[i-2];
            if(curDigit != 0) f[i] += f[i-1];
        }
        return f[s.size()];
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

AI记忆

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

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

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

打赏作者

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

抵扣说明:

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

余额充值