当前位置: 首页 > news >正文

91. 解码方法

递归法:超时了

从字符串的后面向前计算,每一次递归都缩小子集

public class Solution {public int NumDecodings(string s) {return RecursiveAdd(s, s.Length - 1);}public int RecursiveAdd(string s, int index) {// 已经到最后一个元素if(index < 0){return 1;}int count = 0;if(s[index] != '0'){// 将这个元素解码为[1,9]内的数字count = RecursiveAdd(s, index - 1);}// 最后一个数字if(index == 0){return count;}// 将元素解码为两位数int prevIndex = index - 1;if((s[prevIndex] == '1') || (s[prevIndex] == '2' && s[index] <= '6')){count += RecursiveAdd(s, index - 2);}return count;}
}

参考动态规划 :

从字符串的前面向后计算

public class Solution {public int NumDecodings(string s) {int len = s.Length;// a = f[i - 2], b = f[i - 1], c = f[i]int a = 0, b = 1, c = 0;for(int i = 1; i <= len; i++){c = 0;if(s[i - 1] != '0'){c += b;}if(i > 1 && s[i - 2] != '0' && ((s[i - 2] - '0') * 10 + (s[i - 1] - '0') <= 26)){c += a;}a = b;b = c;}return c;}
}

感想:

这两种解法,刚好反映了,递归与动态规划的关系,

递归

n -> n - 1-> ...> 0

   -> n - 2> ...> 0

动态规划

0 ->1->...>n

http://www.lryc.cn/news/133738.html

相关文章:

  • docker搭建opengrok环境2
  • 【校招VIP】java语言考点之ConcurrentHashMap1.7和1.8
  • php如何实现5x+2x+1x=100
  • 机器人项目:从 ROS2 切换到 ROS1 的原因
  • Vault主题 - UiCore多用途Elementor WordPress主题
  • G0第26章:微服务概述与gRPCprotocol buffers
  • 三款远程控制软件对比,5大挑选指标:安全、稳定、易用、兼容、功能
  • Java中static的应用之单例模式
  • TypeError: Cannot read properties of undefined (reading ‘container‘)
  • Vue--BM记事本
  • openpnp - 板子上最小物料封装尺寸的选择
  • 什么是非功能性需求,它们如何影响产品开发?
  • Oracle jdk8 exe->zip
  • Android 命令行如何运行 JAR 文件
  • 5.4 webrtc的线程
  • vscode | linux | c++ intelliense 被弃用解决方案
  • HPE服务器常见报错信息以及解决方案
  • 尚硅谷宋红康MySQL笔记 3-9
  • Leetcode.2337 移动片段得到字符串
  • 【vue】更改角色权限后,实现页面不刷新更改其可展示的导航菜单
  • 【G-LAB】网络工程师常用排错命令详细版
  • Linux 桌面版关闭GUI桌面环境
  • ChatGPT能代替搜索引擎吗?ChatGPT和搜索引擎有什么区别?
  • PHP海外代购管理系统mysql数据库web结构apache计算机软件工程网页wamp
  • 游戏反外挂方案解析
  • 基于郊狼算法优化的BP神经网络(预测应用) - 附代码
  • 【腾讯云 TDSQL-C Serverless 产品测评】全面测评TDSQL-C Mysql Serverless
  • Qt应用开发(基础篇)——纯文本编辑窗口 QPlainTextEdit
  • 数据结构-->栈
  • 强训第36天