【LeetCode 1155】 Number of Dice Rolls With Target Sum

本文探讨了给定两个字符串str1和str2的情况下,如何寻找包含这两个字符串作为子序列的最短字符串。通过动态规划的方法,我们解决了这一问题,并提供了一个具体的代码实现示例。示例中使用了一个三维动态规划数组dp来存储解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If multiple answers exist, you may return any of them.

(A string S is a subsequence of string T if deleting some number of characters from T (possibly 0, and the characters are chosen anywhere from T) results in the string S.)

Example 1:

Input: str1 = "abac", str2 = "cab"
Output: "cabac"
Explanation: 
str1 = "abac" is a subsequence of "cabac" because we can delete the first "c".
str2 = "cab" is a subsequence of "cabac" because we can delete the last "ac".
The answer provided is the shortest such string that satisfies these properties.

Note:

1 <= str1.length, str2.length <= 1000
str1 and str2 consist of lowercase English letters.

思路

动态规划,dp[i][j]表示前i个硬币组成target的方式数目。

代码

class Solution {
public:
    int numRollsToTarget(int d, int f, int target) {
        vector<vector<int>> dp(d+1, vector<int>(target+1));
        int INF = 1e9 + 7;
        
        for (int i=1; i<=min(f, target); ++i) dp[1][i] = 1;
        
        for (int i=2; i<=d; ++i) {
            for (int j=1; j<=min(f, target); ++j) {
                for (int k=1; k<=target-j; ++k) {
                    dp[i][k+j] += dp[i-1][k];
                    dp[i][k+j] %= INF;
                }
            }
        }
        
        return dp[d][target];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值