91. Decode Ways
来源:互联网 发布:意大利2 0西班牙知乎 编辑:程序博客网 时间:2024/05/10 22:39
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.
The naive approach is use dfs:
suppose we have 1123456
the answer should be f(123456) + f(23456)
To improve the performance we could use memory to avoid repeating computation.
Code:
public class Solution { public int numDecodings(String s) { // start, end if(s.equals("")) return 0; HashMap<Integer,Integer> hm = new HashMap(); hm.put(s.length(),1); return search(0,s,hm); } public int search(int start, String s, HashMap<Integer,Integer> hm){ if(hm.containsKey(start)){ return hm.get(start); } int i = s.charAt(start) - '0'; if(i == 0){ hm.put(start, 0); return 0; } int ans = search(start + 1, s, hm); if(start + 1 < s.length()){ i = i * 10 + s.charAt(start + 1) - '0'; if(i <= 26){ ans += search(start + 2, s, hm); } } hm.put(start, ans); return ans; }}
The is actually the same using DP:
if(s[i] == '0') dp[i] = 0;
else{
DP[i] = DP[i + 1] + ((s[i]*10 + s[i + 1] <= 26) ? DP[i + 2] : 0)
0 0
- Leetcode 91. Decode Ways&&639.Decode ways
- [Leetcode] 91. Decode Ways
- LeetCode --- 91. Decode Ways
- [LeetCode]91.Decode Ways
- [leetcode] 91.Decode Ways
- 91. Decode Ways
- Algorithms-91.Decode Ways
- [leetcode] 91. Decode Ways
- 91. Decode Ways
- Leetcode 91. Decode Ways
- 91. Decode Ways
- leetcode 91. Decode Ways
- 91. Decode Ways
- 91. Decode Ways
- Leetcode 91. Decode Ways
- leetcode 91. Decode Ways
- LeetCode 91. Decode Ways
- 91. Decode Ways
- mysql 用 @rownum := @rownum+1 实现 rownum 功能
- mysql + shell 随机字符的产生方法
- Codeforces 779B(暴力)
- LeetCode 23. Merge k Sorted Lists
- Java集合源码阅读笔记-LinkedList
- 91. Decode Ways
- AsyncTask异步任务
- ISLR第四章-logistic LDA QDA
- hibernate many-to-one // one-to-many
- 数据结构与算法之单向链表 <一>
- 谷歌浏览器插件的安装
- jsp 导出xls,创建多个sheet
- Activity的生命周期-----史上最详细的
- UVA 156 筛选不重复单词, map