Saturday, March 2, 2013

[LeetCode] Distinct Subsequences

Thought:
Use a 2D dynamic programming.

Code:
public class Solution {
    public int numDistinct(String S, String T) {
        int m = S.length();
        int n = T.length();
        int[][] result = new int[m + 1][n + 1];
        result[0][0] = 1;
        for(int i = 1; i < m + 1; i++) {
            for(int j = 0; j < n + 1; j++) {
                result[i][j] = result[i - 1][j];
                if(j > 0 && S.charAt(i - 1) == T.charAt(j - 1)) result[i][j] += result[i - 1][j - 1];
            }
        }
        return result[m][n];
    }
}

No comments:

Post a Comment