[LeetCode OJ] Decode Ways

來源:互聯網
上載者:User

標籤:style   blog   color   strong   for   io   

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" (12).

The number of ways decoding "12" is 2.

分析:

方法一:

看完題目之後首先想到了用遞迴的方法來解決這個問題,但是對於比較長的字串出現了TLE(逾時),下面是用遞迴實現的代碼,這種方法的思想很簡單,但是很耗時。

 1 void getnum(string s, int &num) 2 { 3     if(s.size()==0 || s.size()==1) 4     { 5         if(s.size()==1 && s[0]==‘0‘) 6             return; 7         num++; 8         return; 9     }10 11     int a,b;12     istringstream in1(s.substr(0,1));13     istringstream in2(s.substr(0,2));14 15     in1>>a;16     in2>>b;17 18     if(a>=1 && a<=9)19         getnum(s.substr(1), num);20     21     if(b>=10 && b<=26)22         getnum(s.substr(2), num);23 }24 25 class Solution {26 public:27     int numDecodings(string s) {28         int num=0;29         getnum(s, num);30         return num;31     }32 };

 

方法二:

動態規劃的思想來分析題目,假設f(n)表示由給定輸入的前n個字元構成的字串所對應的解碼方式個數,用a表示第n個字元所代表的數字,b表示由第n-1個字元和第n個字元所構成的二位元字,

如果a>=1 && a<=9,那麼第n個字元可以單獨解碼,如果b>=10 && b<=26,那麼第n-1個字元和第n個字元可以組合解碼,以下簡稱a可以解碼,b可以解碼。考慮四種情況:

(1)a和b都可以解碼,不難得出,此時,f(n)=f(n-1)+f(n-2);

(2)如果a可以解碼,b不可以解碼時,f(n)=f(n-1);

(3)如果a不可以解碼,b可以解碼時,f(n)=f(n-2);

(4)a和b都不能解碼時,f(n)=0。

這種方法的運行速度很快,運行255個測試例子,耗時72ms,而用方法一耗時好幾分鐘。

 1 class Solution { 2 public: 3     int numDecodings(string s) { 4         if(s.size()==0) 5             return 0; 6  7         int num1=1, num2=0; 8         int a,b; 9         istringstream in1(s.substr(0,1));10         in1>>a;11         if(a>=1 && a<=9)12             num2++;13         if(s.size()==1)14             return num2;15 16         for(unsigned i=2; i<=s.size(); i++)17         {18             istringstream in1(s.substr(i-1,1));19             istringstream in2(s.substr(i-2,2));20             in1>>a;21             in2>>b;22             int temp = num1;23             num1 = num2;24             num2 = 0;25             if(a>=1 && a<=9)26                 num2 += num1;27 28             if(b>=10 && b<=26)29                 num2 += temp;30         }31         return num2;32     }33 };

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.