博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Algorithm -- Dynamic programming] How Many Ways to Decode This Message?
阅读量:4963 次
发布时间:2019-06-12

本文共 1491 字,大约阅读时间需要 4 分钟。

For example we have

'a' -> 1

'b' -> 2

..

'z' -> 26

 

By given "12", we can decode the string to give result "ab" or 'L', 2 ways to decode, your function should return 2 as an answer.

 

Now asking by given "1246", what should be the return number; 

 

The thinking process is somehow like this:

by given "1" -> we got 'a'

by given "" -> we got ""

by given "12345" -> 'a' + decode('2345') or 'L' + decode('345'), therefore number of ways to decode "12345"is the same of decode(2345)+decode(345).

 

Somehow we can see that this is a recursion task, therefore we can use Dynamice Programming + memo way to solve the problem.

const data = "1246";function num_ways(data) {  // k : count from last to beginning  function helper(data, k, memo) {    if (k === 0) {      // if k equals 0, mean only one single digital number left      // means there must be one char      return 1;    }    if (data === "") {      // if data equals empty, then return 1      return 1;    }    if (memo[k] != null) {      return memo[k];    }    const start = data.length - k;    if (data[start] === "0") {      // if sth start as 0, then no char      return 0;    }    let result = helper(data, k - 1, memo);    if (k >= 2 && parseInt(data.slice(start, start + 2), 10) <= 26) {      result += helper(data, k - 2, memo);    }    memo[k] = result;    return result;  }  let memo = [];  return helper(data, data.length, memo);}const res = num_ways(data);console.log(res); // 3

 

转载于:https://www.cnblogs.com/Answer1215/p/10468653.html

你可能感兴趣的文章
JSON遇到的问题
查看>>
float浮动深入理解
查看>>
流程控制之 if 判断
查看>>
OpenCV图像处理篇之边缘检测算子
查看>>
hdu1331Function Run Fun
查看>>
web容器启动后自动执行程序的几种方式比较
查看>>
expdp/impdp 参数说明,中英对照
查看>>
软件工程—团队作业1
查看>>
centos7 关闭默认firewalld,开启iptables
查看>>
UVALive 3989Ladies' Choice(稳定婚姻问题)
查看>>
来一发!!
查看>>
POJ1679The Unique MST(次小生成树)
查看>>
焦作网络赛K-Transport Ship【dp】
查看>>
面试题 —— 面向对象
查看>>
英文语法 —— 句型(定语从句)
查看>>
markdownpad 2 的使用
查看>>
数据结构与算法的实现 —— 结点定义与数据结构的选择
查看>>
N 个互异数的数组的平均逆序数
查看>>
Opencv+Zbar二维码识别(一维码校正)
查看>>
verilog中的for循环问题
查看>>