鱼C论坛

 找回密码
 立即注册
查看: 1608|回复: 0

[学习笔记] leetcode 91. Decode Ways

[复制链接]
发表于 2019-10-18 13:30:07 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. A message containing letters from A-Z is being encoded to numbers using the following mapping:

  2. 'A' -> 1
  3. 'B' -> 2
  4. ...
  5. 'Z' -> 26
  6. Given a non-empty string containing only digits, determine the total number of ways to decode it.

  7. Example 1:

  8. Input: "12"
  9. Output: 2
  10. Explanation: It could be decoded as "AB" (1 2) or "L" (12).
  11. Example 2:

  12. Input: "226"
  13. Output: 3
  14. Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
复制代码


dp solution

  1. class Solution {
  2. public:
  3.     int numDecodings(string s) {
  4.         
  5.         if(s.length() == 0 || s[0] == '0') return 0;
  6.         vector <int> dp(s.length()+1,0);
  7.         dp[0] = 1;
  8.         dp[1] = 1;
  9.         int max1 = 0;
  10.         for(int i = 2; i <= s.length(); i++){
  11.             
  12.             if(s[i-1] >= '1' && s[i-1] < '27'){
  13.                 dp[i] += dp[i-1];
  14.             }
  15.             
  16.             if(s[i-2] == '1' || (s[i-2] == '2' && s[i-1] >= '0' && s[i-1] <= '6')){
  17.                 dp[i] += dp[i-2];
  18.             }
  19.             
  20.             
  21.         }
  22.         return dp[s.length()];
  23.     }
  24. };
复制代码

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-20 12:25

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表