LeetCode | Decode Ways
来源:互联网 发布:pad不能更新软件 编辑:程序博客网 时间:2024/06/05 08:29
题目:
A message containing letters from A-Z
is 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.
思路:
思路1,利用NP的想法递归,但是时间复杂度太大。思路2,为了简化时间复杂度,我们采用动态规划的方法。例如,当我们知道了n-2长度的字符串能够解释的数目以及n-1长度的字符串能够解释的数目时,我们可以判读如下两个条件:
1)若第n个字符在1到9之间,则n长度的字符串能够解释的数目包含n-1长度字符串能够解释的数目。
2)若第n-1个字符与第n个字符可以解释为一个字母时,则n长度的字符串能够解释的数目包含n-2长度字符串能够解释的数目。
代码:
思路1:
class Solution {public:int count; int numDecodings(string s) { if(s.size()==0) { return 0; } count=0; Decode(s,0,0); return count; } void Decode(string s, int begin, int end) { if(begin>=s.size()) { count++; } else if(end>=s.size()) { return; } else { int num=0; for(int i =begin;i<=end;i++) { num*=10; num+=s[i]-'0'; } if(num>=1&&num<=26) { Decode(s,end+1,end+1); } if(num>=1&&num<=2) { Decode(s,begin,end+1); } } }};
思路2
class Solution {public: int numDecodings(string s) { if(s.size() == 0){ return 0; } else if(s.size() == 1){ return s[0] != '0' ? 1 : 0; } else if(s.size() == 2){ return (s[0] != '0' && s[1] != '0'? 1 : 0) + ((s[0] != '0' && (char2int(s[0]) * 10 + char2int(s[1])) <= 26) ? 1 : 0); } int* dp = new int[s.size()]; dp[0] = s[0] != '0' ? 1 : 0; dp[1] = (s[0] != '0' && s[1] != '0'? 1 : 0) + ((s[0] != '0' && (char2int(s[0]) * 10 + char2int(s[1])) <= 26) ? 1 : 0); for(int i = 2; i < s.size(); i++){ dp[i] = 0; if(s[i] != '0'){ dp[i] += dp[i-1]; } if(s[i-1] != '0' && (char2int(s[i-1]) * 10 + char2int(s[i])) <= 26){ dp[i] += dp[i-2]; } } return dp[s.size() - 1]; } int char2int(char c){ return c - '0'; }};
0 0
- Leetcode 91. Decode Ways&&639.Decode ways
- LeetCode: Decode Ways
- [LeetCode]Decode Ways
- LeetCode Decode Ways
- LeetCode : Decode Ways
- [Leetcode] Decode Ways *
- [leetcode] Decode Ways (!!)
- leetcode 17: Decode Ways
- Leetcode: Decode ways
- LeetCode Decode Ways
- [LeetCode]Decode Ways
- [leetcode] Decode Ways
- Leetcode: Decode Ways
- [LeetCode] Decode Ways
- [leetcode]Decode Ways
- LeetCode-Decode Ways
- [leetcode] Decode Ways
- [LeetCode] Decode Ways
- MySql与SqlServer的一些常用用法的差别
- 几个关于Unity3d转ios平台的指导博文
- 黑马程序员_交通灯管理系统
- Android Uevent 分析,从kernel到framework
- JRE “彻底”卸载
- LeetCode | Decode Ways
- Perl语言入门(第五版) 读书笔记(四)---正则表达式
- 黑马程序员--关于泛型的学习总结和心得二
- 关于异步线程AsyncTask
- 动手学Javascript(2)——超过30岁还能做程序员吗?
- 使用 Core Data 将数据显示到表格(不使用.xib 文件)
- Java I/O系统基础知识
- 将一个二维数组行和列元素互换,存到另一个二维数组中
- A. Two Semiknights Meet