Loading

剑指 Offer 46. 把数字翻译成字符串

思路

方法一:暴力法

使用深度优先搜索枚举出全部情况,试探每一种可能性。

 1 class Solution {
 2 public:
 3     int translateNum(int num) {
 4         string s = to_string(num);
 5         int res = 0;
 6         dfs(s, res);
 7         return res;
 8     }   
 9 
10     void dfs(string s, int& res) {
11         if (s.empty()) {
12             res++;
13             return;
14         }
15 
16         for (int i = 1; i <= s.length(); ++i) {
17             //当以0开头时,只有0这一种情况,不能再往后取子串,比如03是非法的,不能翻译
18             if(s[0] == '0') {
19                 dfs(s.substr(i), res);
20                 return;
21             }
22             
23             string sub = s.substr(0, i);
24             int x = stoi(sub);
25             if (x > 0 && x <= 25) {
26                 dfs(s.substr(i), res);
27             }
28             else {
29                 return;
30             }
31 
32         }
33     }
34 };

 

方法二:动态规划

 1 class Solution {
 2 public:
 3     int translateNum(int num) {
 4         string s = to_string(num);
 5         vector<int> f(s.length()+1);
 6 
 7         f[0] = 1;
 8         f[1] = 1;
 9 
10         int len = s.length();
11         for(int i = 2; i <= len; ++i) {
12             string lastTwoStr = s.substr(i-2, 2);
13             int lastTwoNum = stoi(lastTwoStr);
14             if(lastTwoStr[0] != '0' && lastTwoNum > 0 && lastTwoNum <= 25) {
15                 f[i] = f[i-1] + f[i-2];
16             } else {
17                 f[i] = f[i-1];
18             }
19         }
20 
21         return f[len];
22     }   
23 };

 

参考

面试题46. 把数字翻译成字符串(动态规划,清晰图解)

 

posted @ 2020-11-08 18:45  拾月凄辰  阅读(87)  评论(0编辑  收藏  举报