Python | DP with diagrams for beginners
I have created some diagrams to help learners better understand how the dp works.\nWe create dp = [1] + [0] * len(pressedKeys) for dp[0] to become a "base case"
I have created some diagrams to help learners better understand how the dp works.\nWe create ```dp = [1] + [0] * len(pressedKeys)``` for dp[0] to become a "base case". \nAt each continuous number, we append the appropriate letter to reach the "required length".\nTake string "222233" as an example:\n![image](https://assets.leetcode.com/users/images/67828b61-eb60-44cd-bbec-438a1f223934_1651988165.4311492.png)\n\n\n\nSame concept applies when moving to next different number:\n![image](https://assets.leetcode.com/users/images/50a25151-b975-4404-83a9-4b6da3f8cba8_1652146323.6530101.png)\n\n\n```\nclass Solution(object):\n    def countTexts(self, pressedKeys):\n        """\n        :type pressedKeys: str\n        :rtype: int\n        """\n        dp = [1] + [0]*len(pressedKeys)\n        mod = 10**9 + 7\n        for i, n in enumerate(pressedKeys):\n            dp[i+1] = dp[i]\n            # check if is continous\n            if i >= 1 and pressedKeys[i-1] == n:\n                dp[i+1] += dp[i-1]\n                dp[i+1] %= mod\n                if i >= 2 and pressedKeys[i-2] == n:\n                    dp[i+1] += dp[i-2]\n                    dp[i+1] %= mod\n                    # Special case for \'7\' and \'9\' that can have 4 characters combination\n                    if i >= 3 and pressedKeys[i-3] == n and (n == "7" or n == "9"):\n                        dp[i+1] += dp[i-3]\n                        dp[i+1] %= mod\n        return dp[-1]\n```\nCode can be further optimized.\nInspired from https://leetcode.com/problems/count-number-of-texts/discuss/2017760/JavaPython-3-Time-O(n)-space-O(1)-1-pass-DP-codes .\n\n\n
['Python']