[Leetcode] Decode Ways *
来源:互联网 发布:pdf拼接软件 编辑:程序博客网 时间:2024/05/16 04:50
class Solution {public: int numDecodings(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function int total = 0; Decode(s, 0, s.size(), total); return total; } void Decode(string& s, int idx, int length, int& total) { if (length == 0) return; if (idx == length - 1) { if (s[idx] != '0') ++total; return; } if (s[idx] != '0') { Decode(s, idx + 1, length, total); } if (s[idx] == '1' || (s[idx] == '2' && s[idx + 1] <= '6')) { if (idx + 1 == length - 1) { ++total; return; } else { Decode(s, idx + 2, length, total); } } }};
// DPclass Solution {public: int numDecodings(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function if (s.size() == 0) return 0; vector<int> arr(s.size() + 2, 1); for (int i = s.size() - 1; i >= 0; --i) { if (s[i] == '0') arr[i] = 0; else arr[i] = arr[i + 1]; if (i + 1 < s.size() && (s[i] == '1' || (s[i] == '2' && s[i + 1] <= '6'))) arr[i] += arr[i + 2]; } return arr[0]; }};