Hi guys because I'm still confused about recursion, I started challenging myself to solve recursive problem and I'm stuck in this problem.
description of the question:
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
Example 1:
Input: "12"
Output: 2
Explanation: It could be decoded as "AB" (1 2) or "L" (12).
Example 2:
Input: "226"
Output: 3
Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
My solution is(function called Num_Way(String)) :
lets assume I've string "1234" so it's the same to say "1" + decode"234" or "12" +decode("34") so I must do recursively Num_Way, as a result: Num_Way("1234")=Num_Way("1")+Num_Way("234") or Num_Way("12")+Num_Way("34")
but the output is wrong if I write this, I should disregard from "1" and "12" (the digit that I split) and not considering them in the recursion calls...why?! I subproblem by one digit or two digit, if we didn't consider the one digit or two digit that we split the problem by then where did they gone?! and why we are not taking the Num_Way of them?
description of the question:
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
Example 1:
Input: "12"
Output: 2
Explanation: It could be decoded as "AB" (1 2) or "L" (12).
Example 2:
Input: "226"
Output: 3
Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
My solution is(function called Num_Way(String)) :
lets assume I've string "1234" so it's the same to say "1" + decode"234" or "12" +decode("34") so I must do recursively Num_Way, as a result: Num_Way("1234")=Num_Way("1")+Num_Way("234") or Num_Way("12")+Num_Way("34")
but the output is wrong if I write this, I should disregard from "1" and "12" (the digit that I split) and not considering them in the recursion calls...why?! I subproblem by one digit or two digit, if we didn't consider the one digit or two digit that we split the problem by then where did they gone?! and why we are not taking the Num_Way of them?