91. Decode Ways
2016-05-14 23:07
253 查看
A message containing letters from
following mapping:
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message
2) or
The number of ways decoding
题意:字母A-Z对应1-26,则给出一串数字有多少种解法。
思路:dfs + dp
A-Zis being encoded to numbers using the
following mapping:
'A' -> 1 'B' -> 2 ... 'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message
"12", it could be decoded as
"AB"(1
2) or
"L"(12).
The number of ways decoding
"12"is 2.
题意:字母A-Z对应1-26,则给出一串数字有多少种解法。
思路:dfs + dp
class Solution { public: int numDecodings(string s) { vector<int> dp(s.size(), -1); return dfs(s, dp); } int dfs(string s, vector<int>& dp){ if (s.empty()) return 0; if (s[0] == '0'){ dp[s.size() - 1] = 0; return 0; } if (dp[s.size() - 1] != -1){ return dp[s.size() - 1]; } else{ int m = s.size(); if (m == 1){ dp[m - 1] = 1; } else if(m == 2){ if (s[1] == '0'){ if (s[0] == '1' || s[0] == '2'){ dp[m - 1] = 1; } else{ dp[m - 1] = 0; } } else{ if (s[0] == '2' && s[1] > '6') dp[m - 1] = 1; else if (s[0] > '2'){ dp[m - 1] = 1; } else{ dp[m - 1] = 2; } } } else{ if (s[0] =='1' || (s[0]=='2' && s[1]<='6')) dp[m - 1] = dfs(s.substr(1, m - 1), dp) + dfs(s.substr(2, m - 2), dp); else{ dp[m - 1] = dfs(s.substr(1, m - 1), dp); } } return dp[m - 1]; } } };
相关文章推荐
- iBotCloud-小i机器人在微信公众号中实现智能回答
- linux设备号分配
- Mysql存储引擎
- Java中抽象类和接口的区别
- PHP增删改查
- Linux查看磁盘块大小
- 动态规划——problem o
- UBUNTU实战(5)
- 写给想成为前端工程师的同学们
- At least one JAR was scanned for TLDs yet contained no TLDs 解决办法
- 写给想成为前端工程师的同学们
- PHP数据访问
- 如何实现基于框架的选课系统的质量属性
- 关系数据库常用SQL语句语法大全
- JAVA二叉树,给出先序遍历和中序遍历,构造出新的二叉树
- 【步兵 cocos-js】js绑定 && c++调用Js
- 等级保护
- JVM虚拟机和类加载器
- php this -> display
- PHP三大特性-继承