115. Distinct Subsequences
Given a string S and a string T, count the number of distinct subsequences of S which equals T. A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not). Input: S = "rabbbit", T = "rabbit" Output: 3 Explanation: class Solution { public int numDistinct(String s, String t) { int n = s.length(); int m = t.length(); int[][] matrix = new int[m + 1][n + 1]; for(int i = 0; i < matrix[0].length; i++){ matrix[0][i] = 1; } for(int i = 0 ; i < t.length(); i++){ for(int j = 0; j < s.length() ; j++){ if(t.charAt(i) == s.charAt(j)){ matrix[i + 1][j + 1] = matrix[i][j] + matrix[i + 1][j]; }else{ matrix[i + 1][j + 1] = matrix[i + 1][j]; } } } return matrix[m][n]; } } Idea : Build a 2d matrix if the s[I] == t[j]., then Two options: pick the last Char of t, then matrix[I][j] += matrix[I - 1][j - 1] Not pick the last char of t, matrix[I][j] += matrix[I][j - 1] if the s[I] != t[j], matrix[I][j] += matrix[I][j - 1]
posted on 2018-11-06 08:02 猪猪🐷 阅读(83) 评论(0) 收藏 举报
浙公网安备 33010602011771号