【牛客网】 BM69 把数字翻译成字符串(动态规划C++题解)

【牛客网】 BM69 把数字翻译成字符串(动态规划C++题解)

解题思路

  1. 截止到第i位,我们有两种译码方式,即当前数字做为1位独立译码,或者与前一位组成2位数译码。
  2. 将a[i]记为到达第i位时所有的译码方式之和,显然a[i]可以由a[i-1](独立译码)和a[i-2](组合译码)推出。
  3. 如果可以独立译码,即当前位不为0,则记译码方式res1 = a[i-1]。
  4. 如果可以组合译码,即与前一位组成1-26,则记译码方式res2 = a[i-2]。
  5. 截止当前第i位,译码方式之和a[i] = res1 + res2。
  6. 结果为截止第nums.size()-1的译码方式之和,即为a[nums.size()-1]

Code

class Solution {
    
    
  public:
    //判断是否是两位合法数字,0-26
    int isvalid(char x, char y) {
    
    
        if ((x == '1' and y >= '0' and y <= '9') or (x == '2' and y >= '0' and
                y <= '6'))
            return true;
        return false;
    }

    int solve(string nums) {
    
    
        // 动态规划数组
        int a[100] = {
    
    0};
        // 如果输入合法,截至第一位,一定只有一种译码方式
        a[0] = 1;
        // 如果第二位不是0,则译码方式+1,如果第一二位可以组成1-26的数字,译码方式再+1
        int res1 = 0, res2 = 0;
        if (nums[1] != '0') res1 = 1;
        if (isvalid(nums[0], nums[1])) res2 = 1;
        a[1] = res1 + res2;

        // 如果当前位不为0,a[i] += a[i-1]
        // 如果当前为与前一位能组成1-26的数字,a[i] += a[i-2]
        for (int i = 2; i < nums.size(); ++i) {
    
    
            int res1 = 0;
            int res2 = 0;
            if (nums[i] != '0') res1 = a[i - 1];
            if (isvalid(nums[i - 1], nums[i])) res2 = a[i - 2];
            a[i] = res1 + res2;
        }
        return a[nums.size() - 1];
    }
};

猜你喜欢

转载自blog.csdn.net/zhangjiuding/article/details/124432715
今日推荐