[LeetCode] Distinct Subsequences

來源:互聯網
上載者:User

標籤:

Well, a dynamic programming problem. Let‘s first define its state dp[i][j] to be the number of distinct subsequences of t[0..i - 1] in s[0..j - 1]. Then we have the following state equations:

  1. General case 1: dp[i][j] = dp[i][j - 1] if t[i - 1] != s[j - 1];
  2. General case 2: dp[i][j] = dp[i][j - 1] + dp[i - 1][j - 1] if t[i - 1] == s[j - 1];
  3. Boundary case 1: dp[0][j] = 1 for all j;
  4. Boundary case 2: dp[i][0] = 0 for all positive i.

Now let‘s give brief explanations to the four equations above.

  1. If t[i - 1] != s[j - 1], the distinct subsequences will not include s[j - 1] and thus all the number of distinct subsequences will simply be those in s[0..j - 2], which corresponds to dp[i][j - 1];
  2. If t[i - 1] == s[j - 1], the number of distinct subsequences include two parts: those withs[j - 1] and those without;
  3. An empty string will have exactly one subsequence in any string :-)
  4. Non-empty string will have no subsequences in an empty string.

Putting these together, we will have the following simple codes (just like translation :-)):

 1 class Solution { 2 public: 3     int numDistinct(string s, string t) { 4         int m = t.length(), n = s.length(); 5         vector<vector<int>> dp(m + 1, vector<int> (n + 1, 0)); 6         for (int j = 0; j <= n; j++) dp[0][j] = 1; 7         for (int j = 1; j <= n; j++) 8             for (int i = 1; i <= m; i++) 9                 dp[i][j] = dp[i][j - 1] + (t[i - 1] == s[j - 1] ? dp[i - 1][j - 1] : 0);10         return dp[m][n];11     }12 };

Notice that we keep the whole m*n matrix simply for dp[i - 1][j - 1]. So we can simply store that value in a single variable and further optimize the space complexity. The final code is as follows.

 1 class Solution { 2 public: 3     int numDistinct(string s, string t) { 4         int m = t.length(), n = s.length(); 5         vector<int> cur(m + 1, 0); 6         cur[0] = 1; 7         for (int j = 1; j <= n; j++) {  8             int pre = 1; 9             for (int i = 1; i <= m; i++) {10                 int temp = cur[i];11                 cur[i] = cur[i] + (t[i - 1] == s[j - 1] ? pre : 0);12                 pre = temp;13             }14         }15         return cur[m];16     }17 };

 

[LeetCode] Distinct Subsequences

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.