扰乱字码(区间dp)

题目:https://leetcode-cn.com/problems/scramble-string/
参考:https://leetcode-cn.com/problems/scramble-string/solution/c-dong-tai-gui-hua-by-da-li-wang-36/

class Solution {
public:
    bool isScramble(string s1, string s2) {
        /*
        *给出两个长度相等的字符串 s1 和 s2,
        *判断 s2 是否是 s1 的扰乱字符串
        *区间dp
        *定义dp[len][i][j]表示s1.substr(i,len)
        *和s2.substr(j,len)是否能通过扰乱匹配
        *最后答案即为dp[len][1][1]
        */
        int n = s1.length();
        vector<vector<vector<bool> > > dp;
        dp.resize(n+1);
        for(int i = 0;i <= n;i++) {
            dp[i].resize(n+1);
            for(int j = 0;j <= n;j++) {
                dp[i][j].resize(n+1);
            }
        }
        s1 = "#"+s1;
        s2 = "#"+s2;
        for(int i = 1;i <= n;i++)
            for(int j = 1;j <= n;j++) {
                if(s1[i] == s2[j])  dp[1][i][j] = 1;
            }
        for(int len = 2;len <= n;len++) {
            for(int i = 1;i+len-1 <= n;i++) {
                for(int j = 1;j+len-1 <=n;j++) {
                    for(int k = 1;k < len;k++) {
                        if(dp[k][i][j] && dp[len-k][i+k][j+k])
                            dp[len][i][j] = true;
                        if(dp[k][i][j+len-k] && dp[len-k][i+k][j])
                            dp[len][i][j] = true;
                    }
                }
            }
        }
        return dp[n][1][1];
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值