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];
    }
};
相关推荐
2351610 小时前
【LeetCode】146. LRU 缓存
java·后端·算法·leetcode·链表·缓存·职场和发展
tkevinjd13 小时前
反转链表及其应用(力扣2130)
数据结构·leetcode·链表
程序员烧烤15 小时前
【leetcode刷题007】leetcode116、117
算法·leetcode
Swift社区18 小时前
LeetCode 395 - 至少有 K 个重复字符的最长子串
算法·leetcode·职场和发展
Espresso Macchiato18 小时前
Leetcode 3710. Maximum Partition Factor
leetcode·职场和发展·广度优先遍历·二分法·leetcode hard·leetcode 3710·leetcode双周赛167
巴里巴气18 小时前
第15题 三数之和
数据结构·算法·leetcode
西阳未落19 小时前
LeetCode——双指针(进阶)
c++·算法·leetcode
熬了夜的程序员21 小时前
【LeetCode】69. x 的平方根
开发语言·算法·leetcode·职场和发展·动态规划
Swift社区1 天前
LeetCode 394. 字符串解码(Decode String)
算法·leetcode·职场和发展
tt5555555555551 天前
LeetCode进阶算法题解详解
算法·leetcode·职场和发展