LeetCode : Decode Ways
来源:互联网 发布:淘宝线下实体店加盟费 编辑:程序博客网 时间:2024/05/16 10:46
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.
Solution:
DP,
total(i) = total[i-1] + end_with[i - 1];
end_with[i] = total[i -1 ];
where end_with[i ] means the number of ways to decoding with s[i] alone to be a letter.
class Solution {public: int numDecodings(string s) { // Start typing your C/C++ solution below// DO NOT write int main() functionif(s.empty()){return 0;}int count = 0;vector<int> total(s.size());vector<int> end_with(s.size());char ch = s[0];if(ch > '0'){total[0] = 1;end_with[0] = 1;}for(int i = 1; i< s.size(); ++i){if(s[i] > '0'){end_with[i] = total[i-1];total[i] = total[i -1];}int num = atoi(s.substr(i-1, 2).c_str());if (num > 0 && num <=26){total[i] += end_with[i-1];}}return total[s.size() - 1];}};
今天做的时候有想到了一个更清晰的方法。
dp[i] = dp[i-1] + dp[i-2]
class Solution {public: int numDecodings(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function int n = s.size(); if(n == 0) return 0; vector<int> res(n + 1, 0); res[0] = 1; if(s[0] != '0') res[1] = 1; string temp; for(int i = 1; i< n; ++i){ temp = s.substr(i-1, 2); int value = atoi(temp.c_str()); if(s[i] != '0') res[i+1] = res[i]; if(value > 9 && value < 27){ res[i+1] += res[i-1]; } } return res[n]; }};
- 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
- Axure rp 如何安装库
- linux弹出光驱命令
- LINQ实战阅读笔记---第四章熟悉 LINQ to Objects
- 华中科大校赛预赛1606 Naive
- Java开发者PaaS指南
- LeetCode : Decode Ways
- OpenPaas和CloudBees:云端的Java技术
- PaaS云计算产品的选择始于编程语言
- 编程大赛
- 云计算——PaaS创业企业特点分析
- 双十一淘宝、京东服务器瘫痪大揭秘
- PaaS领域未来五年的十大趋势
- 四大Java云计算测评
- 恢复乱码, 使用sublime text2 + python