力扣91.解码方法

题目:biubiu
题意:给一个数字的字符串,1-26分别对应26个大写字符,现在要求对这个字符串解码,问现在有多少解码情况。
思路1:深搜暴力,可以解决这个问题,但是时间复杂度过大。

class Solution {
public:
	void dfs(vector<int>p, int x) {
		if (x == p.size()) {
			this->ans++;
			return;
		}
		dfs(p, x + 1);
		if (x+1<p.size()&&p[x] == 1 && p[x + 1] <= 9)
			dfs(p, x + 2);
		if (x+1<p.size()&&p[x] == 2 && p[x + 1] <= 6)
			dfs(p, x + 2);
		return;
	}
	int numDecodings(string s) {
		if (s[0] == '0')
			return 0;
		vector<int>p;
		int x;
		for (int i = 0; i < s.size(); i++) {
			if (s[i] == '0') {
				x = p.back();
				//cout << i << " " << x << endl;
				if (x > 2)
					return 0;
				x *= 10;
				p.pop_back();
				p.push_back(x);
			}
			else
			   p.push_back((s[i] - '0'));
		}
		this->ans = 0;
		dfs(p, 0);
		return this->ans;
	}
private:
	int ans;
};

思路2:动态规划
动态规划在于找动态方程,如果能找到,题目就很简单,如果找不到,那么就会让人摸不着头脑。

#include<iostream>
#include<string>
#include<vector>
#include<cmath>
#include<map>
#include<unordered_map>
#include<stack>
#include<algorithm>
using namespace std;
class Solution {
public:
	int numDecodings(string s) {
		vector<int>dp(s.size() + 1, 0);
		dp[0] = 1;
		for (int i = 1; i <= s.size(); i++) {
			if (s[i-1] != '0') {
				dp[i] += dp[i - 1];
			}
			//cout << ((s[i - 1] - '0') * 10 + (s[i] - '0')) <<"**"<< endl;
			if (i > 1 && ((s[i - 2] - '0') * 10 + (s[i-1] - '0')) <= 26&& ((s[i - 2] - '0') * 10 + (s[i-1] - '0'))>=10) {
				//cout << i <<"$"<< endl;
				dp[i] += dp[i - 2];
			}
		}
		return dp[s.size()];
	}
};

int main() {
	string str;
	while (cin>>str) {
		Solution s;
		cout << s.numDecodings(str) << endl;
	}
	return 0;
}

如果直接对着这一位字符解码,他现在的解码就和他前一个解码的个数相同,因为数字和字母是一一映射的关系,dp[i]=dp[i-1],如果这个字符和前一个字符构成一个二位数,那么dp[i]=dp[i-2],这个字符就有这两种情况,他们的和就是dp[i]的解。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

赟家小菜鸟

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

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

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

打赏作者

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

抵扣说明:

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

余额充值