{"id":882,"date":"2017-11-20T19:55:21","date_gmt":"2017-11-21T03:55:21","guid":{"rendered":"http:\/\/zxi.mytechroad.com\/blog\/?p=882"},"modified":"2018-08-31T12:23:14","modified_gmt":"2018-08-31T19:23:14","slug":"leetcode-730-count-different-palindromic-subsequences","status":"publish","type":"post","link":"https:\/\/zxi.mytechroad.com\/blog\/dynamic-programming\/leetcode-730-count-different-palindromic-subsequences\/","title":{"rendered":"\u82b1\u82b1\u9171 LeetCode 730. Count Different Palindromic Subsequences"},"content":{"rendered":"<p><iframe loading=\"lazy\" title=\"\u82b1\u82b1\u9171 LeetCode 730. Count Different Palindromic Subsequences - \u5237\u9898\u627e\u5de5\u4f5c EP114\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/UjiFFYU3EKM?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n<p><strong>Problem:<\/strong><\/p>\n<p>Given a string S, find the number of different non-empty palindromic subsequences in S, and\u00a0<b>return that number modulo\u00a0<code>10^9 + 7<\/code>.<\/b><\/p>\n<p>A subsequence of a string S is obtained by deleting 0 or more characters from S.<\/p>\n<p>A sequence is palindromic if it is equal to the sequence reversed.<\/p>\n<p>Two sequences\u00a0<code>A_1, A_2, ...<\/code>\u00a0and\u00a0<code>B_1, B_2, ...<\/code>\u00a0are different if there is some\u00a0<code>i<\/code>\u00a0for which\u00a0<code>A_i != B_i<\/code>.<\/p>\n<p><b>Example 1:<\/b><\/p>\n<pre class=\"crayon:false\">Input: \r\nS = 'bccb'\r\nOutput: 6\r\nExplanation: \r\nThe 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'.\r\nNote that 'bcb' is counted only once, even though it occurs twice.\r\n<\/pre>\n<p><b>Example 2:<\/b><\/p>\n<pre class=\"crayon:false\">Input: \r\nS = 'abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba'\r\nOutput: 104860361\r\nExplanation: \r\nThere are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 10^9 + 7.\r\n<\/pre>\n<p><b>Note:<\/b><\/p>\n<p>&nbsp;<\/p>\n<ul>\n<li>The length of\u00a0<code>S<\/code>\u00a0will be in the range\u00a0<code>[1, 1000]<\/code>.<\/li>\n<li>Each character\u00a0<code>S[i]<\/code>\u00a0will be in the set\u00a0<code>{'a', 'b', 'c', 'd'}<\/code>.<\/li>\n<\/ul>\n<p><script async src=\"\/\/pagead2.googlesyndication.com\/pagead\/js\/adsbygoogle.js\"><\/script><br \/>\n<ins class=\"adsbygoogle\" style=\"display: block; text-align: center;\" data-ad-layout=\"in-article\" data-ad-format=\"fluid\" data-ad-client=\"ca-pub-2404451723245401\" data-ad-slot=\"7983117522\"><\/ins><br \/>\n<script>\n     (adsbygoogle = window.adsbygoogle || []).push({});\n<\/script><\/p>\n<p><strong>Idea:<\/strong><\/p>\n<p>DP<\/p>\n<p><a href=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/730-ep114-1.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-891\" src=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/730-ep114-1.png\" alt=\"\" width=\"960\" height=\"540\" srcset=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/730-ep114-1.png 960w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/730-ep114-1-300x169.png 300w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/730-ep114-1-768x432.png 768w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/730-ep114-1-624x351.png 624w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/a><\/p>\n<p><a href=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/730-ep114-2.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-890\" src=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/730-ep114-2.png\" alt=\"\" width=\"960\" height=\"540\" srcset=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/730-ep114-2.png 960w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/730-ep114-2-300x169.png 300w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/730-ep114-2-768x432.png 768w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/730-ep114-2-624x351.png 624w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/a><\/p>\n<p><ins class=\"adsbygoogle\" style=\"display: block; text-align: center;\" data-ad-layout=\"in-article\" data-ad-format=\"fluid\" data-ad-client=\"ca-pub-2404451723245401\" data-ad-slot=\"7983117522\">\u00a0<\/ins><\/p>\n<h1><strong>Solution 1: Recursion with memoization<\/strong><\/h1>\n<p>Time complexity: O(n^2)<br \/>\nSpace complexity: O(n^2)<\/p>\n<div class=\"responsive-tabs\">\n<h2 class=\"tabtitle\">C++<\/h2>\n<div class=\"tabcontent\">\n\n<pre class=\"lang:c++ decode:true \">\/\/ Author: Huahua\r\n\/\/ Runtime: 72 ms\r\nclass Solution {\r\npublic:\r\n    int countPalindromicSubsequences(const string&amp; S) {\r\n        const int n = S.length();\r\n        m_ = vector&lt;vector&lt;int&gt;&gt;(n + 1, vector&lt;int&gt;(n + 1, 0));\r\n        return count(S, 0, S.length() - 1);\r\n    }\r\nprivate:\r\n    static constexpr long kMod = 1000000007;\r\n    long count(const string&amp; S, int s, int e) {\r\n        if (s &gt; e) return 0;\r\n        if (s == e) return 1;        \r\n        if (m_[s][e] &gt; 0) return m_[s][e];        \r\n        \r\n        long ans = 0;\r\n        if (S[s] == S[e]) {\r\n            int l = s + 1;\r\n            int r = e - 1;\r\n            while (l &lt;= r &amp;&amp; S[l] != S[s]) ++l;\r\n            while (l &lt;= r &amp;&amp; S[r] != S[s]) --r;\r\n            if (l &gt; r)\r\n                ans = count(S, s + 1, e - 1) * 2 + 2;\r\n            else if (l == r)\r\n                ans = count(S, s + 1, e - 1) * 2 + 1;\r\n            else\r\n                ans = count(S, s + 1, e - 1) * 2 \r\n                    - count(S, l + 1, r - 1);\r\n        } else {\r\n            ans = count(S, s, e - 1)\r\n                + count(S, s + 1, e)\r\n                - count(S, s + 1, e - 1);\r\n        }\r\n        \r\n        return m_[s][e] = (ans + kMod) % kMod;\r\n    }\r\n    \r\n    \r\n    vector&lt;vector&lt;int&gt;&gt; m_;\r\n};<\/pre>\n\n<\/div><h2 class=\"tabtitle\">Python<\/h2>\n<div class=\"tabcontent\">\n\n<pre class=\"lang:python decode:true\">\"\"\"\r\nAuthor: Huahua\r\nRuntime: 3582 ms\r\n\"\"\"\r\nclass Solution:\r\n    def countPalindromicSubsequences(self, S):\r\n        def count(S, i, j):\r\n            if i &gt; j: return 0\r\n            if i == j: return 1\r\n            if self.m_[i][j]: return self.m_[i][j]\r\n\r\n            if S[i] == S[j]:\r\n                ans = count(S, i + 1, j - 1) * 2\r\n                l = i + 1\r\n                r = j - 1\r\n                while l &lt;= r and S[l] != S[i]: l += 1\r\n                while l &lt;= r and S[r] != S[i]: r -= 1\r\n                if l &gt; r: ans += 2\r\n                elif l == r: ans += 1\r\n                else: ans -= count(S, l + 1, r - 1)                \r\n            else:\r\n                ans = count(S, i + 1, j) + count(S, i, j - 1) - count(S, i + 1, j - 1)\r\n\r\n            self.m_[i][j] = ans % 1000000007\r\n            return self.m_[i][j]\r\n        \r\n        n = len(S)\r\n        self.m_ = [[None for _ in range(n)] for _ in range(n)]\r\n        return count(S, 0, n - 1)\r\n<\/pre>\n\n<\/div><h2 class=\"tabtitle\">Java<\/h2>\n<div class=\"tabcontent\">\n\n<pre class=\"lang:java decode:true \">\/\/ Author: Huahua\r\n\/\/ Runtime: 107 ms\r\nclass Solution {\r\n    private int[][] m_;\r\n    private static final int kMod = 1000000007;\r\n    public int countPalindromicSubsequences(String S) {\r\n        int n = S.length();\r\n        m_ = new int[n][n];\r\n        return count(S.toCharArray(), 0, n - 1);\r\n    }\r\n    \r\n    private int count(char[] s, int i, int j) {\r\n        if (i &gt; j) return 0;\r\n        if (i == j) return 1;\r\n        if (m_[i][j] &gt; 0) return m_[i][j];\r\n        \r\n        long ans = 0;\r\n        \r\n        if (s[i] == s[j]) {\r\n            ans += count(s, i + 1, j - 1) * 2;\r\n            int l = i + 1;\r\n            int r = j - 1;\r\n            while (l &lt;= r &amp;&amp; s[l] != s[i]) ++l;\r\n            while (l &lt;= r &amp;&amp; s[r] != s[i]) --r;\r\n            if (l &gt; r) ans += 2;\r\n            else if (l == r) ans += 1;\r\n            else ans -= count(s, l + 1, r - 1);\r\n        } else {\r\n            ans = count(s, i, j - 1) \r\n                + count(s, i + 1, j) \r\n                - count(s, i + 1, j - 1);\r\n        }\r\n        \r\n        m_[i][j] = (int)((ans + kMod) % kMod);\r\n        return m_[i][j];\r\n    }\r\n}<\/pre>\n<\/div><\/div>\n<h1><strong>Solution 2:\u00a0DP<\/strong><\/h1>\n<div class=\"responsive-tabs\">\n<h2 class=\"tabtitle\">C++<\/h2>\n<div class=\"tabcontent\">\n\n<pre class=\"lang:default decode:true \">\/\/ Author: Huahua\r\n\/\/ Runtime: 79 ms\r\nclass Solution {\r\npublic:\r\n    int countPalindromicSubsequences(const string&amp; S) {\r\n        int n = S.length();\r\n        vector&lt;vector&lt;int&gt;&gt; dp(n, vector&lt;int&gt;(n, 0));\r\n        for (int i = 0; i &lt; n; ++i)\r\n            dp[i][i] = 1;\r\n        \r\n        for (int len = 1; len &lt;= n; ++len) {\r\n            for (int i = 0; i &lt; n - len; ++i) {\r\n                const int j = i + len;                \r\n                if (S[i] == S[j]) {\r\n                    dp[i][j] = dp[i + 1][j - 1] * 2;                        \r\n                    int l = i + 1;\r\n                    int r = j - 1;\r\n                    while (l &lt;= r &amp;&amp; S[l] != S[i]) ++l;\r\n                    while (l &lt;= r &amp;&amp; S[r] != S[i]) --r;                    \r\n                    if (l == r) dp[i][j] += 1;\r\n                    else if (l &gt; r) dp[i][j] += 2;\r\n                    else dp[i][j] -= dp[l + 1][r - 1];\r\n                } else {\r\n                    dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1]; \r\n                }\r\n                \r\n                dp[i][j] = (dp[i][j] + kMod) % kMod;\r\n            }\r\n        }\r\n        \r\n        return dp[0][n - 1];\r\n    }\r\nprivate:\r\n    static constexpr long kMod = 1000000007;    \r\n};<\/pre>\n\n<\/div><h2 class=\"tabtitle\">Pyhton<\/h2>\n<div class=\"tabcontent\">\n\n<pre class=\"lang:python decode:true \">\"\"\"\r\nAuthor: Huahua\r\nRuntime: 3639 ms\r\n\"\"\"\r\nclass Solution:\r\n    def countPalindromicSubsequences(self, S):        \r\n        n = len(S)\r\n        if n == 0: return 0        \r\n        dp = [[0 for _ in range(n)] for _ in range(n)]\r\n        for i in range(n): dp[i][i] = 1\r\n            \r\n        for size in range(2, n + 1):\r\n            for i in range(n - size + 1):\r\n                j = i + size - 1                \r\n                if S[i] == S[j]:\r\n                    dp[i][j] = dp[i + 1][j - 1] * 2\r\n                    l = i + 1\r\n                    r = j - 1\r\n                    while l &lt;= r and S[l] != S[i]: l += 1\r\n                    while l &lt;= r and S[r] != S[i]: r -= 1\r\n                    if l &gt; r: dp[i][j] += 2\r\n                    elif l == r: dp[i][j] += 1\r\n                    else: dp[i][j] -= dp[l + 1][r - 1]\r\n                else:\r\n                    dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1] \r\n                dp[i][j] %= 1000000007\r\n            \r\n        return dp[0][n - 1]\r\n<\/pre>\n<\/div><\/div>\n<p><strong>Related Problems:<\/strong><\/p>\n<ul>\n<li><a href=\"http:\/\/zxi.mytechroad.com\/blog\/dynamic-programming\/leetcode-664-strange-printer\/\">[\u89e3\u9898\u62a5\u544a] LeetCode 664. Strange Printer<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Problem: Given a string S, find the number of different non-empty palindromic subsequences in S, and\u00a0return that number modulo\u00a010^9 + 7. A subsequence of a&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[46],"tags":[8,18,217,95],"class_list":["post-882","post","type-post","status-publish","format-standard","hentry","category-dynamic-programming","tag-counting","tag-dp","tag-hard","tag-palindrome","entry","simple"],"_links":{"self":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/882","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/comments?post=882"}],"version-history":[{"count":17,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/882\/revisions"}],"predecessor-version":[{"id":3787,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/882\/revisions\/3787"}],"wp:attachment":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/media?parent=882"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/categories?post=882"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/tags?post=882"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}