---
# System prepended metadata

title: 0727. Minimum Window Subsequence
tags: [Leetcode, Dynamic Programming, Hard]

---

# 0727. Minimum Window Subsequence
###### tags: `Leetcode` `Hard` `Dynamic Programming`
Link: https://leetcode.com/problems/minimum-window-subsequence/
## 思路
```dp[i][j] => s[1:i]```里最短的、并且包含```t[1:j]```的substring的长度(这个substring必须要求以```s[i]```结尾)
注意边界条件的设定
```dp[i][0]=0```
```dp[0][j]=Integer.MAX_VALUE/2``` 因为不可能使得s2是s1的子串
## Code
```java=
class Solution {
    public String minWindow(String s1, String s2) {
        int m = s1.length(), n = s2.length();
        int[][] dp = new int[m+1][n+1];
        for(int i=0; i<=m; i++) Arrays.fill(dp[i], Integer.MAX_VALUE/2);
        for(int i=0; i<=m; i++) dp[i][0] = 0;
        
        for(int i=1; i<=m; i++){
            for(int j=1; j<=n; j++){
                if(s1.charAt(i-1)==s2.charAt(j-1)){
                    dp[i][j] = dp[i-1][j-1]+1;
                }
                else dp[i][j] = dp[i-1][j]+1;
            }
        }
        
        int len = Integer.MAX_VALUE/2, idx = -1;
        for(int i=1; i<=m; i++){
            if(len>dp[i][n]){
                len = dp[i][n];
                idx = i-1;
            }
        }
        return idx==-1?"":s1.substring(idx-len+1, idx+1);
    }
}
```