Distinct Subsequences(不同的子序列)

http://www.lintcode.com/zh-cn/problem/distinct-subsequences/?rand=true

public class Solution {
    /*
     * @param : A string
     * @param : A string
     * @return: Count the number of distinct subsequences
     */
    public int numDistinct(String S, String T) {
        // write your code here
        if (S == null || T == null) {
            return 0;
        }
        int[][] nums = new int[S.length() + 1][T.length() + 1];
//        nums[i][j]表示 S有i个字符,T有j个字符时,可形成的子集个数
//        i为0的时候子集为0,j为0时子集为1
        for (int i = 0; i < nums.length; i++) {
            nums[i][0] = 1;
        }
        for (int i = 1; i < nums.length; i++) {
            for (int j = 1; j < nums[0].length; j++) {
                if (S.charAt(i - 1) == T.charAt(j - 1)) {
//                    如果这两个字符相同,个数应该是前一个的个数,再加上一组的个数,
//                    可以这么理解,因为它们相同,所以同时把这一位删除,如果存在子集,那么加上也存在子集。
                    nums[i][j] = nums[i - 1][j] + nums[i - 1][j - 1];
                } else {
//                    如果这两个字符不同,那么个数就应该是前一个的个数
                    nums[i][j] = nums[i - 1][j];
                }
            }
        }
        return nums[S.length()][T.length()];
    }
};

你可能感兴趣的:(Distinct Subsequences(不同的子序列))