Decode Ways
来源:互联网 发布:淘宝万能评价语 编辑:程序博客网 时间:2024/05/17 06:13
非常类似于上楼梯问题,一次可以选择上一阶,也可以选择上两阶,最后问有多少种上法。
但是这个题要难一些,因为要判断0出现的地方以及策略,但是实际上如果想清楚的话也很简单。
使用一个递归函数,参数start为将要处理的下标。
- 如果start为字符串长度,说明已经到末尾,这样便有一种译码方法,返回1;
- 如果start指示位置为0,或者大于字符串长度,说明start位置不合法,没有译码方法,返回0(这一条要仔细思考一下,为何大于字符串长度就不合法了?);
- 如果start指示位置为1,那么无论如何在这里都有两条路可走,一条是向前走一步,把1单独译码成A,另一条是向前走两步,将这两条路所有方法数加起来即可;
- 如果start位置是2,则需要判断是否到了末尾以及下一位是不是比7小,这样才能决定此处能走几步;
- 其他情况就只能走一步了。
class Solution {public: int numDecodings(string s) { if (s.length() == 0) return 0; vector<int> DP(s.length(), -1); return helper(s, 0, DP); } int helper(string s, int start, vector<int> &DP) { if (start == s.length()) return 1; if (s[start] == '0' || start > s.length()) return 0; if (DP[start] != -1) return DP[start]; if (s[start] == '1') { DP[start] = helper(s, start + 1, DP) + helper(s, start + 2, DP); return DP[start]; } if (s[start] == '2') { if (start + 1 == s.length() || s[start + 1] >= '7') { DP[start] = helper(s, start + 1, DP); return DP[start]; } else { DP[start] = helper(s, start + 1, DP) + helper(s, start + 2, DP); return DP[start]; } } DP[start] = helper(s, start + 1, DP); return DP[start]; }};
http://oj.leetcode.com/problems/decode-ways/
0 0
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Ubuntu 上安装MySQLdb for Python
- 色彩深度(colordepth)
- C#学习5
- 黑马程序员--集合类总结1
- js之匿名函数
- Decode Ways
- asterisk语音信箱voicemail.conf
- 全解析jQuery插件开发!很好很强大!
- C++ 多线程编程 & OpenMP
- 第十四章 REST解惑——REST简介
- Direct-attached storage (DAS)
- text-align简单理解
- hive 初始化运行流程
- [Linux]Fedora 20 MySQL安装配置