题源:LeetCode
链接:https://leetcode-cn.com/problems/decode-ways
这也是一道动态规划的题目,注意f(x)和f(x-1)、f(x-2)的关系
1 class Solution { 2 public: 3 int numDecodings(string s) { 4 int n = s.size(); 5 vector<int> f(n + 1); 6 f[0] = 1; 7 for (int i = 1; i <= n; ++i) { 8 if (s[i - 1] != '0') { 9 f[i] += f[i - 1]; 10 } 11 if (i > 1 && s[i - 2] != '0' && ((s[i - 2] - '0') * 10 + (s[i - 1] - '0') <= 26)) { 12 f[i] += f[i - 2]; 13 } 14 } 15 return f[n]; 16 } 17 };