數字解碼方法數問題
阿新 • • 發佈:2017-05-16
pub highlight str pre 編碼 sta else if bsp ngs (12).
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"
The number of ways decoding "12"
is 2.
==============================昏割線========================
本來是自己想了半天的劃分情況,修修改改,總是要遺漏情況,懟上代碼,不做分析。
public static int numDecodings(String s) { // Write your code here if(0 == s.length()) return 0; if(s.charAt(0)==‘0‘) return 0; if(s.length() == 1) return 1; int []dp = new int[s.length()];//記錄遍歷到字符串第i位置時的狀態(該狀態指的是編碼的方法數) dp[0] = 1; for(int i=1;i<s.length();i++){ String temp = s.substring(i-1, i+1);// 取i位和i-1位 int num = Integer.parseInt(temp); if(num == 0){ return 0; }else if(1 <= num && num <= 9) dp[i] = dp[i-1]; else if(11 <= num && num <= 19 || num >=21 && num <= 26) dp[i] = dp[i-1] + (i - 2 >= 0 ? dp[i-2] : 1); else if(num % 10 == 0) if(num/10 >= 3 ) return 0; else dp[i] = i - 2 >= 0 ? dp[i-2] : 1; else dp[i] = dp[i-1]; } return dp[s.length()-1]; }
鐺鐺鐺鐺鐺鐺!推出較優解:
另f[i] 表示 在 i 位置時,解碼的方法數。顯然,f[i] 可由之前的2個狀態得出。
① 選擇單獨解碼第i個位置,此時,f[i] = f[i-1]
② 選擇解碼i 和i - 1 位置, 此時, f[i] = f[i - 2]
class Solution { public: int decodeOne(char one) { return (one == ‘0‘) ? 0 : 1; // 判斷單個字符能否解碼 } int decodeTwo(char one, char two) { if( (one == ‘1‘) || (one == ‘2‘ && two <= ‘6‘) ) // 判斷雙字符的解碼情況 return 1; else return 0; } int fun(string s, int i) { if(i == 0 ) return decodeOne(s[0]); // 只有1個字符,直接判斷 if(i == 1) return ( decodeOne(s[0]) & decodeOne(s[1]) ) + decodeTwo(s[0], s[1]); // 2個字符, 先單個, 再2個 if(i >= 2) { int sum = 0; if(decodeOne(s[i])) sum += fun(s, i-1); if(decodeTwo(s[i-1], s[i]) ) sum += fun(s, i-2); return sum; } } int numDecodings(string s) { if(s.size() == 0 || s[0] == ‘0‘) return 0; return fun(s, s.size() - 1); } };
數字解碼方法數問題