方法一: 动态规划
class Solution { public boolean isInterleave(String s1, String s2, String s3) { int n1 = s1.length(), n2 = s2.length(), n3 = s3.length(); if(n1 + n2 != n3) return false; char[] arr1 = s1.toCharArray(), arr2 = s2.toCharArray(), arr3 = s3.toCharArray(); boolean[][] dp = new boolean[n1+1][n2+1]; dp[0][0] = true; for(int i = 1; i <= n1; i++) { if(dp[i-1][0] && arr1[i-1] == arr3[i-1]) dp[i][0] = true; } for(int i = 1; i <= n2; i++) { if(dp[0][i-1] && arr2[i-1] == arr3[i-1]) dp[0][i] = true; } for(int i = 1; i <= n1; i++) { for(int j = 1; j <= n2; j++) { if(arr1[i-1] == arr3[i+j-1]) { dp[i][j] = dp[i-1][j]; } if(arr2[j-1] == arr3[i+j-1]) { dp[i][j] = dp[i][j] || dp[i][j-1]; } } } return dp[n1][n2]; } }
方法二:记忆化回溯
class Solution { char[] arr1; char[] arr2; char[] arr3; public boolean isInterleave(String s1, String s2, String s3) { int n1 = s1.length(), n2 = s2.length(), n3 = s3.length(); if(n1 + n2 != n3) return false; visited = new boolean[n1+1][n2+1]; arr1 = s1.toCharArray(); arr2 = s2.toCharArray(); arr3 = s3.toCharArray(); return dfs(0,0,0); } boolean[][] visited; public boolean dfs(int i, int j, int k) { if(k == arr3.length) return true; if(visited[i][j]) return false; else if(i < arr1.length && arr1[i] == arr3[k] && dfs(i+1,j,k+1)) return true; else if(j < arr2.length && arr2[j] == arr3[k] && dfs(i,j+1,k+1)) return true; visited[i][j] = true; return false; } }