File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
leetcode/cpp/dynamic programming Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Decode ways
2
+
3
+ class Solution {
4
+ public:
5
+ bool check (string s, int i){
6
+ int num = (s[i-1 ] - ' 0' )*10 + (s[i] - ' 0' );
7
+ if (num>=10 && num<=26 )return true ;
8
+ return false ;
9
+ }
10
+
11
+ int numDecodings (string s) {
12
+ if (s.length () == 0 )return 0 ;
13
+ vector<int > dp (s.length ()+1 , 0 );
14
+ dp[0 ] = 1 ;
15
+ if (s[0 ]>' 0' ){
16
+ dp[1 ] = 1 ;
17
+ }
18
+ else {
19
+ return 0 ;
20
+ }
21
+ if (s.length () == 1 )return s.length ();
22
+ for (int i=1 ;i<s.length ();i++){
23
+ if (s[i] == ' 0' && s[i-1 ]>' 0' && s[i-1 ]<' 3' ){
24
+ dp[i+1 ] = dp[i-1 ];
25
+ }
26
+ else if (s[i] == ' 0' ){
27
+ return 0 ;
28
+ }
29
+ else if (check (s, i)){
30
+ dp[i+1 ] = dp[i-1 ] + dp[i];
31
+ }
32
+ else {
33
+ dp[i+1 ] = dp[i];
34
+ }
35
+ }
36
+ return dp[s.length ()];
37
+ }
38
+ };
You can’t perform that action at this time.
0 commit comments