动规_97.交错字符串(20200718)

常规 & 解析

/** 1. 显然是动规
	2. 状态转移:
		p = i + j - 1; 
		2.1 dp[i][j] |= (dp[i - 1][j] && s1[i - 1] == s3[p]);
        2.2 dp[i][j] |= (dp[i][j - 1] && s2[j - 1] == s3[p]);  
	3. 定义 : 
		3.1  p 对应 s3 中串的位置
		3.2  dp[i][j] 动规其实就是暴力遍历了啦,你懂的
		3.3  对两组状态转移不就是对应从 s1 串中取得还是从 s2 串中取得吗?
	4. base case 
		4.1 dp[0][0] = true;一开始还未进行匹配当然是 true
		4.2 dp[0][j] |= (dp[0][j - 1] && s2[j - 1] == s3[j - 1]); j > 1
		4.3 dp[i][0] |= (dp[i-1][0] && s1[i - 1] == s3[i - 1]); i > 1

*/

class Solution {
public:
    bool isInterleave(string s1, string s2, string s3) {
        int n = s1.size(), m = s2.size(), t = s3.size();
    
        if (n + m != t) {
            return false;
        }
        bool dp[n+1][m+1];
        memset(dp, 0, sizeof(dp));
        
        // base case
        dp[0][0] = true;
        for (int j = 1; j <= m; j++) {
            dp[0][j] |= (dp[0][j - 1] && s2[j - 1] == s3[j - 1]);
        }
        for (int i = 1; i <= n; i++) {
            dp[i][0] |= (dp[i-1][0] && s1[i - 1] == s3[i - 1]);
        }

        // 状态转移
        for (int i = 1; i <= n; ++i) {
            for (int j = 1; j <= m; ++j) {
                int p = i + j - 1; // 对应 s3 串中位置
                
                dp[i][j] |= (dp[i - 1][j] && s1[i - 1] == s3[p]);
                dp[i][j] |= (dp[i][j - 1] && s2[j - 1] == s3[p]);  
            }
        }
        return dp[n][m];
    }
};



状压

// 状压版本
// 移动一步只需保存上一层状态
class Solution {
public:
    bool isInterleave(string s1, string s2, string s3) {

        int n = s1.size(), m = s2.size(), t = s3.size();
        
        if (n + m != t) {
            return false;
        }
        bool f[m+1];
        memset(f, 0, sizeof(f));
        f[0] = true;
        for (int i = 0; i <= n; i++) {
            for (int j = 0; j <= m; j++) {
                int p = i+j-1;
                if(i > 0) {
                    f[j] &= (s1[i-1] == s3[p]);
                }
                if(j > 0) {
                    f[j] |= (f[j-1] && s2[j-1] == s3[p]);
                }
            }
        }
        return f[m];
    }
};

你可能感兴趣的:(Miracle,wandering,in,LeetCode)