leetcode 87: Scramble String

Learned the 3D dp algorithm from http://blog.sina.com.cn/leetcode. dp[i][j][l] means starting from i in s1 and j in s2, if they can be scambled with the length l. When l goes from 1 to len-max(i,j), it has already initialized the dp array. If I let i and j loop from 1 to len-1, the dp array must be initialized first when l equals to 1.

class Solution {
public:
    bool isScramble(string s1, string s2) {
        int len=s1.length();
        vector<bool> a(len+1,0);
        vector<vector<bool> > b(len,a);
        vector<vector<vector<bool> > > dp(len,b);
        for(int i=len-1;i>=0;i--)
            for(int j=len-1;j>=0;j--)
                for(int l=1;l<=len-max(i,j);l++)
                {
                    if(s1.substr(i,l)==s2.substr(j,l))
                        dp[i][j][l]=1;
                    else
                    {
                        for(int c=1;c<l;c++)
                            if(dp[i][j][c]&&dp[i+c][j+c][l-c]||dp[i][j+l-c][c]&&dp[i+c][j][l-c])
                            {
                                dp[i][j][l]=1;
                                break;
                            }
                    }
                }
        return dp[0][0][len];
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值