Leetcode, DecodeWays
#include <iostream>
#include <string>
using namespace std;
//类似Climb Staris, f(n) = f(n - 1) + f(n - 2)
//动规,时间复杂度 O(n),空间复杂度 O(1)
int solution(const string &s)
{
if (s.empty() || s[0] == '0')
return 0;
int prev = 0;
int cur = 1;
for ( int i = 1; i <= s.size(); ++i)
{
if (s[i - 1] == '0')
cur = 0;
//取了两位,则prev为0
if (i < 2 || !(s[i - 2] == '1' || (s[i - 2] == '2' && s[i - 1] <= '6')))
prev = 0;
int tmp = cur;
cur += prev;
prev = tmp;
}
return cur;
}
int main()
{
cout << solution("12") << endl; //2
cout << solution("123") << endl; //3
cout << solution("103") << endl; //1
return 0;
}