leetcode Decode Ways
2014-05-07 14:05
274 查看
A message containing letters from
the following mapping:
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message
2) or
The number of ways decoding
思路:
1.和 restore ip address 题意几乎一致, 不过这道题不要打印路径, 所以, dp 更适合。用前者dfs的方法会导致超市。
2 用动态规划的思路,找到转移函数
Count[i] = Count[i-1] if S[i-1] is a valid char
or = Count[i-1]+ Count[i-2] if S[i-1] and S[i-2] together is still a valid char.
A-Zis 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.
思路:
1.和 restore ip address 题意几乎一致, 不过这道题不要打印路径, 所以, dp 更适合。用前者dfs的方法会导致超市。
2 用动态规划的思路,找到转移函数
Count[i] = Count[i-1] if S[i-1] is a valid char
or = Count[i-1]+ Count[i-2] if S[i-1] and S[i-2] together is still a valid char.
int check(char one){ return (one != '0') ? 1:0; } int check(char one, char two){ return (one =='1' || (one=='2'&& two<='6'))?1:0; } int numDecodings(string s){ if(s.size()<=0 || s[0]=='0') return 0; if(s.size()==1 && s[0]!='0') return 1; vector<int> dp(s.size(),0); dp[0] = check(s[0]); dp[1] = (check(s[0])*check(s[1]))+check(s[0],s[1]); for(int i=2; i<s.size(); i++){ if(check(s[i])){ dp[i] += dp[i-1]; } if(check(s[i-1],s[i])){ dp[i] += dp[i-2]; } } return dp[s.size()-1]; }
相关文章推荐
- python简介FTP模块
- 【LeetCode】Clone_Graph
- 【Compute Vision】学习OpenCV——KeyPoint Matching 优化方式
- HTML <select>标签
- A. Squats
- DB2 数据库创建、IXF格式 表的导出导入。
- 团购三巨头承诺“誓言”:诚意够足,效率如何?
- meta program (1) swap_iter
- 用GDB调试程序
- 张小龙 微信事业群
- ajax解析结合json格式
- DB_LINK的个人理解
- C++模板类头文件和实现文件分离的方法(vs2012测试)
- HTML5中5个简单实用的API(第二篇,含全屏、可见性、拍照、预加载、电池状态)
- 析构函数出错
- 使用 CocoStudio 创建 Cocos2d-x 序列帧和骨骼动画
- 同步异步与阻塞非阻塞
- ios摇一摇功能
- ASP + ACCESS 上传图片到数据库与将图片读出数据库显示之实现
- Javascript中的setInterval和setTimeout的使用总结