leetcode 115. 不同的子序列

题目:115. 不同的子序列 - 力扣(LeetCode)

动态规划问题,f[i][j]表示s的第i个元素匹配到t的第j个元素,有多少种结果

f[i][j] = f[i - 1][j] + (s[i] == t[j] ? f[i - 1][j - 1] : 0)

答案就是 f[s.length() - 1][t.length() - 1]

cpp 复制代码
#define _MAX_ (1000000007)
class Solution {
public:
    int numDistinct(string s, string t) {
        int n = (int) s.length();
        int m = (int) t.length();
        uint32_t** f = (uint32_t**) malloc(n * sizeof(uint32_t*));
        for (int i = 0; i < n; i++) {
            f[i] = (uint32_t*) malloc(m * sizeof(uint32_t));
        }
        for (int i = 0; i < n; i++) {
            if (s[i] == t[0]) {
                f[i][0] = 1;
            } else {
                f[i][0] = 0;
            }
            if (i > 0) {
                f[i][0] += f[i - 1][0];
                uint32_t a = f[i][0];
                uint32_t b = f[i - 1][0];
                if (f[i][0] >= _MAX_) {
                    f[i][0] %= _MAX_;
                }
            }
            for (int j = 1; j < m; j++) {
                if (i > 0) {
                    f[i][j] = f[i - 1][j];
                } else {
                    f[i][j] = 0;
                }
                if (s[i] == t[j] && i > 0) {
                    f[i][j] += f[i - 1][j - 1];
                    if (f[i][j] >= _MAX_) {
                        f[i][j] %= _MAX_;
                    }
                }
            }
        }
//        for (int i = 0; i < n; i++) {
//            for (int j = 0; j < m; j++) {
//                printf("%d ", f[i][j]);
//            }
//            printf("\n");
//        }
        return f[n - 1][m - 1];
    }
};
相关推荐
Nontee29 分钟前
Leetcode Top100答案和解释 -- Python版本(链表)
算法·leetcode·链表
章小幽2 小时前
LeetCode-35.搜索插入位置
数据结构·算法·leetcode
x_xbx3 小时前
LeetCode:111. 二叉树的最小深度
算法·leetcode·职场和发展
滴滴答滴答答4 小时前
机考刷题之 10 LeetCode 200 岛屿数量
算法·leetcode·职场和发展
luckycoding7 小时前
3005. 最大频率元素计数
算法·leetcode·职场和发展
一叶落4387 小时前
LeetCode 67. 二进制求和(C语言详解 | 双指针模拟加法)
c语言·数据结构·算法·leetcode
逆境不可逃8 小时前
LeetCode 热题 100 之 279. 完全平方数 322. 零钱兑换 139. 单词拆分 300. 最长递增子序列
java·算法·leetcode·职场和发展
滴滴答滴答答9 小时前
机考刷题之 12 LeetCode 684 冗余的边
算法·leetcode·职场和发展
codeyanwu9 小时前
LeetCode Hot 100 -- 图论
leetcode·深度优先·图论