[Algorithm -- Dynamic programming] How Many Ways to Decode This Message?

本文探讨了解码数字字符串为字母的多种方式,通过动态规划和记忆化递归的方法,解决了给定数字字符串的不同解码方式计数问题。以1246为例,详细解析了算法实现过程。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值