Leetcode 动态规划 Decode Ways

来源:互联网 发布:传奇霸业胸章属性数据 编辑:程序博客网 时间:2024/05/17 03:08

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie


Decode Ways

 Total Accepted: 8689 Total Submissions: 55465

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.




题意:将A-B编码为1-26,现在给一串数字,问有多少种解码方式
思路:动态规划
设f[i]表示以第i个字符结尾的数字串的解码方式,则
如果 s[i - 2]是1 或 s[i - 2]是2且s[i - 1]小于6,f[i] = f[i - 1] + f[i - 2] 
否则,f[i] = f[i - 1]
此外,还要再加一些判断
如果s[i - 1]是零,则以s[i - 2]数字结尾的解码方式为零。因为s[i - 2]数字必须和s[i - 1]结合起来
实现的时候只要两个变量保存前两个的值,即f[i - 1]和f[i - 2]
注:动态规划,除了那些最后要从所有的f[i]中选出最大最小值的问题,
都只需要用几个变量保存前几个值即可。这样实现不仅省空间,而且不用担心
下标越界

--》其实即使是要求最值的问题,也可以用一个变量表示当前最值,然后在循环中每次更新

复杂度:时间O(n), 空间O(1)

class Solution {public:    int numDecodings(string s) {    if (s.empty() || s[0] == '0') return 0;    int pre = 0, cur = 1;    for(int i = 1; i <= s.size(); i++){    int cur_digit = s[i - 1] - '0';    int pre_digit = s[i - 2] - '0';        if(cur_digit == 0) cur = 0; //如果当前数字是零,则以前面一个数字结尾的解码方式为零。因为前一个数字必须和当前数字结合起来        int temp = cur;        if(pre_digit == 1 || (pre_digit == 2 && cur_digit <= 6)){    cur = pre + cur;    }        pre = temp;    }    return cur;        }};


0 0