-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path91.decode-ways.cpp
58 lines (46 loc) · 1.04 KB
/
91.decode-ways.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
* @lc app=leetcode id=91 lang=cpp
*
* [91] Decode Ways
*/
// @lc code=start
#include <algorithm>
#include <iostream>
#include <memory.h>
#include <stack>
#include <unordered_map>
#include <utility>
#include <vector>
using namespace std;
class Solution {
public:
int dfs(int index, string str, unordered_map<int, int>& dp) {
if (index == str.length()) {
return 1;
}
if (str.at(index) == '0') {
return 0;
}
if (index == str.length() - 1) {
return 1;
}
auto iter = dp.find(index);
if (iter != dp.end()) {
return iter->second;
}
int cnt = dfs(index + 1, str, dp);
if (stoi(str.substr(index, 2)) <= 26) {
cnt += dfs(index + 2, str, dp);
}
dp.insert({ index, cnt });
return cnt;
}
int numDecodings(string s) {
if (s.length() == 0) {
return 0;
}
unordered_map<int, int> dp;
return dfs(0, s, dp);
}
};
// @lc code=end