[Algorithm -- Dynamic programming] 91. Decode Ways <How Many Ways to Decode This Message?>

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
复制代码

 

posted @   Zhentiw  阅读(298)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2016-03-04 [CSS] CSS Transitions: Delays and Multiple Properties
2016-03-04 [ReactJS] DOM Event Listeners in a React Component
2015-03-04 [Javascript + lodash] sortBy and sortedIndex
2015-03-04 [Javascript] Webpack Loaders, Source Maps, and ES6
点击右上角即可分享
微信分享提示