Monday, September 9, 2013

Distinct Subsequence@leetcode

刷题必备书籍Cracking the Coding Interview: 150 Programming Questions and Solutions 

简历:The Google Resume: How to Prepare for a Career and Land a Job at Apple, Microsoft, Google, or any Top Tech Company
算法学习书籍:Introduction to Algorithms
编程珠玑:Programming Pearls (2nd Edition)
C++ 学习:The C++ Programming Language, 4th Edition
经典操作系统书籍,龙书:Operating System Concepts
创业:The Start-up of You: Adapt to the Future, Invest in Yourself, and Transform Your Career
Given a string S and a string T, count the number of distinct subsequences of T in S.
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).
Here is an example:
S = "rabbbit"T = "rabbit"
Return 3.
» Solve this problem

I use DP and has the same idea of Palindrome Partitioning. Use a vector to dynamically tracking the number we get.

    r a b b b i t
  1 1 1 1 1 1 1 1
0 1 1 1 1 1 1 1
a 0 1 1 1 1
b 0 0 2 3 3 3
b 0 0 0 0 3 3 3
i 0 0 0 0 0 0 3 3
t 0 0 0 0 0 0 0 3  

This table shows clearly of how it algorithm works. We compare from first to end, once we found two chars equal, then we add 1 to result. Because if this two chars equal, it means that we can delete it or keep it. 

We may use 2 dimensional vectors to do it, while now we do it in just one 1 dimensional. 

2 comments:

  1. Hello, came across your solution while random surfing. It seems that in your second solution, you are looping m*n times to update the record matrix. A lot of those operations will be 0+=0 which seems somewhat unnecessary.

    I think you can optimize it a bit by scanning T first and create a hash table to track a list of indices for each letter. This way you only need to look up the indices and update accordingly. Same worst case performance(all identical letters), but on average you will get it much faster.

    ReplyDelete
  2. Great Explanation and very neat code .. Thanks

    ReplyDelete

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...