LeetCode 91. Decode Ways

人工智能-CS188 Project 2: Multi-agents 一、项目介绍 项目介绍网页 项目代码下载 本项目是采用Berkeley的CS188课程内容实习二的内容,在这个项目中,我们将为经典版本的Pacman 设计自动算法,包括幽灵。在此过程中,我们将实现 minimax 和 expectimax 搜索并尝试评估函数设计 完成作业只需要完成5个题目,按照项目介绍的步骤进行完成,主要是在multiAgents.py文件中进行补充代码 二、代码详情 1、Question1:Reflex Agent 略 2、Question2:Minimax 套用ppt上的minm 阅读详情

There are two ways to solve this problem. One is to solve it front-back, the other is back-front.

I currently only wrote the back-front method:

Suppose we have such a string:    a0, a1, a2.... ai, ai+1, ai+2...an-1

Suppose we have get that from an-1, an-2...ai+2, the ways of decoding such a sequence is dp[i+2]

There are three conditions to consider:

1: if ai == 1, we dont need to care about ai+1, the ways to decode is 1+ dp[i+2];

2: if ai == 2, ai+1 should be smaller than '6', the ways to decode is 1 + dp[i+2].

3: if ai == 2, ai+1 greater than '6', the ways to decode is dp[i+1].

Think that, decode a individual number is 1, but 0 has no way to decode, thus, 0.

So, we can have the dynamic function:  dp[i] = dp[i] + dp[i+2] if(s[i] == 1 || s[i] == 2 && s[i + 1] < '6')

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

/*
  A message containing letters from A-Z is being encoded to numbers using the following mapping:
  'A' --> 1
  'B' --> 2
  ....
  'Z' --> 26
  Given an encoded message containing digits, determine the total number of ways to decode it.
  For example:
  Given encoded message "12", it could be decoded as "AB" or "L". 
  The number of ways decoding "12" is 2.
*/
/*
  Analyze: 
  Several example will make this question clear.
  "102" --> "10", "2" -> total method is 1
  "12" --> {"1", "2"}, "12" --> total method is 2.
  "127" --> {"1", "2", "7"}, {"12", "7"} --> total method is 2
  "126" --> {"1", "2", "6"}, {"12", "6"}, {"1", "26"}--> total method is 3.
  There are several cases need special attentions.
  1: "1"/"2" + "0", the char "0" can be interpreted as a decode way.
  2: "2" + "7, 8, 9" can only be interpreted as one way.
*/

int numDecodings(string s) {
  int n = s.size();
  vector<int> dp(n+2, 1);
  for(int i = s.size() - 1; i >= 0; --i) {
    if(s[i] == 0) dp[i] = 0;
    else dp[i] = dp[i + 1];

    if(i + 1 < s.size() && (s[i] == '1' || (s[i] == '2' && s[i+1] <= '6'))) {
      dp[i] += dp[i+2];
    }
  }
  return dp[0];
}



int main(void) {
  cout << "123" << " decode ways: "<< numDecodings("123") << endl;
  cout << "102" << " decode ways: "<< numDecodings("102") << endl;
  cout << "127" << " decode ways: "<< numDecodings("127") << endl;
}


To visualize the problem.... Everytime, we can decode two chars or one chars.


'0' is a special case to case, there are two cases that we might encounter '0'.  However, no matter where we have 0, the corresponding decode way will 0.

#include <string>
#include <vector>
#include <iostream>
using namespace std;
// decode it from back to front.
int decodeWays(string str, int len) {
  if(len == 0 || len == 1) return 1;
  int num = 0;
  if(str[len - 1] > '0') // this line should be commented out! for the case "10000000" == 1
    num = decodeWays(str.substr(0, len - 1), len - 1);
  if(str[len - 2] == '1' || ((str[len - 2] == '2') && str[len - 1] < '6'))
    num += decodeWays(str.substr(0, len - 2), len - 2);
  return num;
}

// dp
int decodeWaysII(string str) {
  int n = str.size();
  vector<int> dp(n + 1, 0);
  dp[0] = dp[1] = 1;
  for(int i = 2; i <= n; ++i) {
    if(str[i - 1] > '0') {
      dp[i] = dp[i-1];
    }
    if(str[i-2] == '1' || (str[i-2] == '2' && str[i-1] < '6'))
      dp[i] += dp[i-2];
  }
  return dp[n];
}

// to simplify more
int decodeWaysIII(string str) {
  int n = str.size();
  if(n <= 1) return 1;
  int prev = 1;
  int curr = 1;
  int sum = 0;
  for(int i = 2; i <= n; ++i) {
    if(str[i-1] == '0') prev = 0;
    if(str[i-2] != '1' && !(str[i-2] == '2' && str[i-1] < '6'))
      curr = 0;
    sum = curr + prev;
    prev = curr;
    curr = sum;
  }
  return curr;
} 


Another ways is more cool! and space efficient!

// In-place ways
int decodeWays(string str) {
  if(str[0] == '0') return 0;
  int prev = 0;
  int curr = 1;
  for(int i = 1; i <= str.size(); ++i) {
    if(s[i-1] == '0') curr = 0;
    if(i < 2 || !(s[i-2] == '1' || (s[i-2] == '2' && s[i-1] <= '6')))
      prev = 0;

    int tmp = curr;
    curr = curr + prev;
    prev = tmp;
  }
  return curr;
}

reference: http://www.acmerblog.com/leetcode-solution-decode-ways-6209.html

Another variation: Asked by Amazon,  return all the decoded strings, better to use backtracking, the time complexity is T(n) = T(n-1) + T(n-2) Thus it is 2^N

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

void decodeWays(string str, int pos, string path, vector<string>& res, unordered_map<string, char>& dict) {
  if(pos > str.size()) return;
  if(pos == str.size()) {
    res.push_back(path);
    return;
  }
  for(int i = 1; i <= 2; ++i) {
    string tmp = str.substr(pos, i);
    if(dict.count(tmp)) {
      decodeWays(str, pos + i, path + dict[tmp], res, dict);
    }
  }
}

vector<string> decodeWays(int input, unordered_map<string, char>& dict) {
  string str = to_string(input);
  if(str.size() == 0) return {};
  vector<string> res;
  string path = "";
  decodeWays(str, 0, path, res, dict);
  return res;
}
int main(void) {
  unordered_map<string, char> dict {
    {"1", 'A'},
    {"2", 'B'},
    {"3", 'C'},
    {"4", 'D'},
    {"5", 'E'},
    {"6", 'F'},
    {"7", 'G'},
    {"8", 'H'},
    {"9", 'I'},
    {"10", 'J'},
    {"11", 'K'},
    {"12", 'M'},
    {"13", 'N'},
    {"14", 'O'},
    {"15", 'P'},
    {"16", 'Q'},
    {"17", 'R'},
    {"18", 'S'},
    {"19", 'T'},
    {"20", 'U'},
    {"21", 'V'},
    {"22", 'W'},
    {"23", 'X'},
    {"24", 'Y'},
    {"25", 'Z'}};
  vector<string> res = decodeWays(123, dict);
  for(int i = 0; i < res.size(); ++i) cout << res[i] << endl;
}


如何使用 Python 爬虫获取猫眼电影数据:电影评分与评论分析 随着互联网的快速发展,越来越多的人开始使用各种在线平台来了解电影信息,猫眼电影作为一个非常流行的在线电影票务平台,提供了详细的电影评分、评论和票房数据。本篇博客将详细介绍如何使用 Python 爬虫技术获取猫眼电影平台上的电影数据,重点关注电影评分和用户评论的爬取,分析其背后的数据处理和反爬虫技术。如果你对数据分析、电影评论分析等话题感兴趣,可以根据本文的示例进一步深入挖掘更多的数据,为决策提供支持,或为电影产业的相关研究提供有价值的分析依据。有些猫眼电影的页面数据是动态加载的,使用。 阅读详情

相关推荐

DDR内存Prefetch机制详解:从DDR1到DDR4的技术演进与性能提升

本文深入解析DDR内存Prefetch机制从DDR1到DDR4的技术演进与性能提升。通过分析Prefetch技术的实现原理与Burst传输的协同机制,揭示DDR1的2n Prefetch、DDR2的4n Prefetch、DDR3的8n Prefetch以及DDR4的Bank Group架构创新如何显著提升内存带宽与系统性能。

weixin_30369041的博客 537

LeetCode91——Decode Ways

Decode ways 一维动态规划,考虑条件限制

上善若水 2070

ARTIX-7 GTP 3G-SDI 工程构建与调试实战

本文详细介绍了基于ARTIX-7 FPGA和GTP收发器的3G-SDI工程构建与调试实战。从基础概念解析到Vivado工程创建、GTP IP核配置、SDI IP核集成,再到系统集成与时钟域处理,提供了全面的技术指导。文章还分享了调试技巧、常见问题排查方法以及性能验证步骤,帮助开发者快速掌握3G-SDI视频传输技术的实现与优化。

weixin_30443813的博客 256

【LeetCode】91. Decode Ways

91. Decode Ways Description: A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -&gt; 1 'B' -&gt; 2 ... 'Z' -&gt; 26 Given a non-empty string con...

Microstrong 1568

ARM的CI-700和Arteris的NoC对比

设计理念:CI-700注重于为移动和客户端SoC提供定制化的互连解决方案,而Arteris的NoC更侧重于提供灵活、可配置的网络互连技术,适用于多种应用场景。性能与功耗:CI-700通过系统级缓存和网状拓扑结构优化性能和功耗,而Arteris的NoC通过物理感知和多协议支持来提升性能和降低功耗。功能安全:Arteris的NoC提供了功能安全支持,这对于汽车和工业应用尤为重要,而CI-700虽然也关注安全性,但未明确提及功能安全支持。互操作性。

ygyglg的专栏 2619

用人话讲明白线性回归LinearRegression

目录 什么是回归 一元线性回归 损失函数 最小二乘估计 小结 1. 什么是回归 当我们学习一门新课程、接触一个新专业时,总会对该领域的专有名词感到困惑,甚至看完解释仍难以理解其含义。在我们一起学习machine learning的过程中,我会尽量对相关名词用“人话”做一遍解释,以减少学习的“痛苦感”。 譬如今天要学的线性“回归”,这个回归(regression)和我们平时说的“回归祖国”的回...

化简可得 1万+

LeetCode91 Decode Ways

LeetCode91 Decode Ways 问题来源LeetCode91 问题描述 A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given an encoded message

yanqinghe123的专栏 303

Android Studio运行报错: failed to load include path ……\platforms\android-35\android.jar的最细解决方案

【代码】Android Studio运行报错: failed to load include path ……\platforms\android-35\android.jar的最细解决方案。

2401_86789230的博客 2万+

LeetCode 91. Decode Ways 题解

本题是动态规划的经典应用,与爬楼梯问题类似,但增加了更多的约束条件。状态定义:dp[i] 表示前 i 个字符的解码方法数状态转移:考虑单独解码和组合解码两种情况边界条件:'0' 不能单独解码,也不能作为组合的开头通过本题可以深入理解带约束条件的动态规划问题。

cannonjinx的博客 1149

岭回归的MATLAB步骤

MATLAB 实现框架,它涵盖了从数据导入到岭回归的步骤,包括计算共线性、使用 MAE、MSE、R²、MAPE 进行评价,以及绘制相应的可视化图表。

subject625Ruben的博客 1089

scratch绘制四个三角形 2024年6月中国电子学会 图形化编程 scratch编程等级考试二级真题和答案解析

​ scratch绘制四个三角形 一、题目要求 2024年6月电子学会图形化编程Scratch等级考试二级真题 1、准备工作 1.保留默认角色小猫; 2.添加背景Stars。 2、功能实现 1 .隐藏角色小猫,设置画笔裙始位置为(0,0),画笔颜色为黄色,画笔的粗细为5; 2. 点击绿旗,绘制如下图所示图形,三角形的边长为50。 二、案例分析 1、角色分析 角色:小猫 2、背景分析 背景:Stars背景 3、前期准备 1. 保留默认的小猫不变 ​

青少年编程学习指导 1716

Leetcode 91 Decode Ways

思路:遍历string,每次可选择一个数字或两个数字。然后利用recursive方法。如果选一个数字,那么numDecodings(s.substring(i+1));如果选两个数字,那么numDecodings(s.substring(i+2))。那么此时就是把两种情况的结果加起来,就是最后的答案。今天心情很差,我的思路和标答思路完全一样,代码也写出来了,挺顺利的,但是就一直time limit exceeed。我就花了很多时间优化,但是最后还是不行。后来看了别人的思路及代码。我们的思路是一样的。我觉得.

GoodJobJasper的博客 198

炼金术士的试炼:2026年企业信用信息公示系统极验五维反爬下的Python数据博弈与破局之道

企业信用信息公示系统(以下简称“公示系统”)作为国家市场监督管理总局权威发布平台,承载着全国亿万市场主体的登记、许可、处罚等核心信用数据。对于金融风控、市场分析、商业尽职调查等领域,这些数据具有不可替代的黄金价值。然而,公示系统在2025年至2026年间进行了数次史诗级的安全加固,构建了包含动态令牌、极致混淆的JavaScript混淆、无感行为指纹、智能语义验证码以及WebAssembly防护在内的“五维反爬长城”。

2201_76125261的博客 348

LeetCode 91. Decode Ways 渣渣学算法系列

LeetCode 91. Decode WaysJava实现(这是个low13的尝试)参考的学习视频地址:https://www.bilibili.com/video/av27893462/?p=3&amp;amp;amp;amp;t=2563//该题为划分类动态规划.代码如下:还需改进 Java实现(这是个low13的尝试) 参考的学习视频地址:https://www.bilibili.com/video/av2789...

dajin5776的博客 618

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

LeetCode 91. Decode Ways(递推)

题目来源:https://leetcode.com/problems/decode-ways/ 问题描述 91.Decode Ways Medium A message containing letters fromA-Zis being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2...

da_kao_la的博客 242

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

LeetCode—91. Decode Ways

LeetCode—91. Decode Ways 题目 https://leetcode.com/problems/decode-ways/description/ 找出字符串的解码方式数。 思路及解法 动态规划的题目。 我们用dp[i]表示到前i个字符,总计的解码方式。 考虑递归关系。s[i]的值是我们需要关心的问题,如果它是0,此时s[i]必须和s[i-1]组合,所以需要去看s[i-1]的值...

pnnngchg的博客 355

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

【Leetcode】91. 解码方法(Decode Ways)

Leetcode - 91 Decode Ways (Medium) 题目描述:给定一个字符串,字母 A - Z 可以分别解码成 1 - 26,求字符串共有几种解码方法。 Input: "226" Output: 3 Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). 解题思路:要注意 0...

厉兵秣码 318

【LeetCode】#91解码方法(Decode Ways)

【LeetCode】#91解码方法(Decode Ways) 题目描述 一条包含字母 A-Z 的消息通过以下方式进行了编码: ‘A’ -&gt; 1 ‘B’ -&gt; 2 … ‘Z’ -&gt; 26 给定一个只包含数字的非空字符串,请计算解码方法的总数。 示例 示例 1: 输入: “12” 输出: 2 解释: 它可以解码为 “AB”(1 2)或者 “L”(12)。 示例 2: 输入: “226...

weixin_43858604的博客 200

Leetcode-91. Decode Ways

Leetcode-91.Decode Ways 题目: A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given an encoded message contain

caoyan_12727的博客 615

Leetcode 91. Decode Ways (Medium) (cpp)

Leetcode 91. Decode Ways (Medium) (cpp)

还是需要多学习!闷声大发财,这是坠吼的! 544

[LeetCode]91.Decode Ways

题目 A message containing letters from A-Z is being encoded to numbers using the following mapping: ‘A’ -&gt; 1 ‘B’ -&gt; 2 … ‘Z’ -&gt; 26 Given an encoded message containing digits, determine th...

SmartSi 334

【LeetCode】91. Decode Ways 解题报告(Python)

【LeetCode】91. Decode Ways 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/decode-ways/descripti...

负雪明烛 5307

算法学习之动态规划(leetcode 91 Decode Ways)

leetcode 91. Decode Ways A message containing letters from A-Z is being encoded to numbers using the following mapping:'A' -> 1 'B' -> 2 ... 'Z' -> 26Given an encoded message containing digits, determ

maxiaotiaoti的专栏 514

leetcode 91.Decode Ways

leetcode 91.Decode Ways 题目: A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -&gt; 1 'B' -&gt; 2 ... 'Z' -&gt; 26 Given a non-empty string containing...

wyxwyx469410930的博客 159

【DFS + 记忆化递归 + DP】LeetCode 91. Decode Ways

LeetCode 91. Decode Ways Solution1:我的答案 还是记录一下,最容易想到的是DFS,但是在第223/238个case上就超时了。。。 class Solution { public: int numDecodings(string s) { //先来一波DFS int res = 0, start = 0; my_num...

Allenlzcoder的博客 858
上一篇: LeetCode 331. Verify Preorder Serialization of a Binary Tree
下一篇: LeetCode 278. First Bad Version
ActiveCoder
博客等级 码龄11年 4粉丝 345原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值