码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-03-04 09:16:33      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:some   algo   last   class   think   ref   ESS   AMM   UNC   

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) {
    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);

    if (k >= 2 && parseInt(data.slice(start, start + 2), 10) <= 26) {
      result += helper(data, k - 2);
    }

    memo[k] = result;

    return result;
  }

  let memo = [];
  return helper(data, data.length, memo);
}

const res = num_ways(data);
console.log(res);

 

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

标签:some   algo   last   class   think   ref   ESS   AMM   UNC   

原文地址:https://www.cnblogs.com/Answer1215/p/10468653.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!