639. Decode Ways II
2018-01-14 03:05
357 查看
1. Description
Given a string only containing numbers and '*', return the total number of ways to decode it.
'*' can be treated as 1 to 9.
2. Solution
Dynamic Programming.
dp[i] refers to the number of ways to decode the first i elements in the string.
3. Code
Given a string only containing numbers and '*', return the total number of ways to decode it.
'*' can be treated as 1 to 9.
2. Solution
Dynamic Programming.
dp[i] refers to the number of ways to decode the first i elements in the string.
3. Code
int mod = 1000000007; int numDecodings(string s) { int n = s.size(); if(n==0) return 0; long dp[n+1]; dp[0]=1; if(s[0]=='0') dp[1]=0; else if(s[0]=='*') dp[1]=9; else dp[1]=1; for(int i=2;i<=n;i++){ dp[i]=0; if(s[i-1]!='0'){ if(s[i-1]=='*') dp[i]=((dp[i-1]%mod)*9)%mod; else dp[i]=dp[i-1]%mod; } if(s[i-2]=='0') continue; if(s[i-2]>'0'&&s[i-2]<='9'&&s[i-1]>='0'&&s[i-1]<='9'){ string str; str+= s[i-2]; str+= s[i-1]; int a = atoi(str.c_str()); if(a<=26 && a>0) dp[i]+=(dp[i-2]%mod); dp[i]=dp[i]%mod; continue; } if(s[i-2]=='*'&&s[i-1]>='0'&&s[i-1]<='9'){ dp[i]+=(dp[i-2]%mod);//s[i-2]==1 if(s[i-1]>='0'&&s[i-1]<='6') dp[i]+=(dp[i-2]%mod);//s[i-2]==2 dp[i]=dp[i]%mod; continue; } if(s[i-1]=='*'&&s[i-2]>'0'&&s[i-2]<='2'){ if(s[i-2]=='1') dp[i]+=((9*(dp[i-2]%mod)%mod)); else if(s[i-2]=='2') dp[i]+=((6*(dp[i-2]%mod))%mod);//s[i-2]==2 dp[i]=dp[i]%mod; continue; } if(s[i-2]=='*'&&s[i-1]=='*'){ dp[i]+=(((dp[i-2]%mod)*15)%mod); dp[i]=dp[i]%mod; continue; } } return dp ; }
相关文章推荐
- 639. Decode Ways II
- [LeetCode] 639. Decode Ways II 解码方法 II
- leetcode 639 Decode Ways II
- leetcode 639. Decode Ways II 解码方法+动态规划DP+无论如何也不会做
- LeetCode 639. Decode Ways II
- 639. Decode Ways II
- [Leetcode] 639. Decode Ways II 解题报告
- [LeetCode]Decode Ways II
- [LeetCode] Decode Ways II 解码方法之二
- Decode Ways II
- LeetCode解题报告—— Word Search & Subsets II & Decode Ways
- Leetcode 91. Decode Ways&&639.Decode ways
- Decode Ways II
- 动态规划小结 - 一维动态规划 - 时间复杂度 O(n),题 [LeetCode] Jump Game,Decode Ways
- LeetCode | Decode Ways
- LeetCode(90)Decode Ways
- Decode Ways
- LeetCode 091: Decode Ways
- leetcode由易入难——【4】Decode Ways
- LeetCode Decode Ways