{"id":21,"date":"2020-12-20T20:09:44","date_gmt":"2020-12-20T20:09:44","guid":{"rendered":"http:\/\/feellikelearning.com\/en\/?p=21"},"modified":"2020-12-20T20:09:45","modified_gmt":"2020-12-20T20:09:45","slug":"algorithms-practice-leetcode-322-coin-change","status":"publish","type":"post","link":"https:\/\/feellikelearning.com\/en\/index.php\/2020\/12\/20\/algorithms-practice-leetcode-322-coin-change\/","title":{"rendered":"ALGORITHMS PRACTICE LEETCODE 322 Coin Change"},"content":{"rendered":"\n<p><a href=\"https:\/\/leetcode.com\/problems\/coin-change\/\">Here<\/a> is the question.<\/p>\n\n\n\n<p>I came up with the answer without looking the answer, bottom up dynamic programming (dp) is not a very easy to design at the beginning. Starting from top down + cache, I wrote it a few times, and simplified it a little bit each time, and finally passed the OJ.<\/p>\n\n\n\n<p>Python version.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Solution(object):\n    def coinChange(self, coins, amount):\n        \"\"\"\n        :type coins: List&#91;int]\n        :type amount: int\n        :rtype: int\n        \"\"\"\n        cache = {0:0}\n        self.dfs(coins, amount, cache)\n        return cache&#91;amount]\n        \n    def dfs(self, coins, amount, cache):\n        if amount in cache:\n            return cache&#91;amount]\n        if amount == 0:\n            return 0\n        if amount &lt; 0:\n            return -1\n        ans = float('inf')\n        for coin in coins:\n            rest_cnt = self.dfs(coins, amount - coin, cache)\n            if rest_cnt != -1:\n                ans = min(ans, rest_cnt + 1)\n        if ans == float('inf'):\n            cache&#91;amount] = -1\n            return -1\n        \n        cache&#91;amount] = ans\n        return ans <\/code><\/pre>\n\n\n\n<p>In order to better understand the algorithm, I added some logs to record how many times dfs was called and cache hits, and the number of times each cache key was written (with cache and without cache).<\/p>\n\n\n\n<p>Use coins = [1, 2, 5] and amount = 11 as an example<\/p>\n\n\n\n<p>With cache<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>dfs call: 34\ncache hit: 15\nkey write times\n1: 1\n2: 1\n3: 1\n4: 1\n5: 1\n6: 1\n7: 1\n8: 1\n9: 1\n10: 1\n11: 1<\/code><\/pre>\n\n\n\n<p>without cache<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>dfs call: 928\ncache hit: 0\nkey write times\n1: 128\n2: 75\n3: 44\n4: 26\n5: 15\n6: 9\n7: 5\n8: 3\n9: 2\n10: 1\n11: 1<\/code><\/pre>\n\n\n\n<p>The contents of the cache after running are as follows<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>0: 0\n1: 1\n2: 1\n3: 2\n4: 2\n5: 1\n6: 2\n7: 2\n8: 3\n9: 3\n10: 2\n11: 3<\/code><\/pre>\n\n\n\n<p>Numbers inside cache are exactly the minimum numbers of coins needed for the target amount from 0 to 11. From this, I think that bottom up dp is exactly what needs to be built for the above cache. dp[0] = 0, the amount is 0, of course,  0 coin is needed to make up a value of 0. dp[amount] depends on whether the value of <code>amount-coin<\/code> is positive, and whether there is a value other than -1 before. When the amount is being calculated, the previous <code>dp[0]<\/code> to <code>dp[amount-coin]<\/code> have been filled in. For all possible coin values, find smallest value of <code>dp[amount \u2013 coin],<\/code> of course, <code>amount - coin<\/code> needs to be larger or equal to 0 and <code>dp[amount \u2013 coin]<\/code> is not -1, add 1 to it, and you will get <code>dp[amount]<\/code>. The time complexity is <code>O(amount * len(coins))<\/code>. The space is <code>O(amount)<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Solution(object):\n    def coinChange(self, coins, amount):\n        \"\"\"\n        :type coins: List&#91;int]\n        :type amount: int\n        :rtype: int\n        \"\"\"\n        dp = &#91;0] * (amount + 1)\n        for i in range(1, amount + 1):\n            rest_min_cnt = -1\n            for coin in coins:\n                rest = i - coin\n                if rest >= 0 and dp&#91;rest] != -1:\n                    if rest_min_cnt == -1:\n                        rest_min_cnt = dp&#91;rest]\n                    else:\n                        rest_min_cnt = min(rest_min_cnt, dp&#91;rest])\n            dp&#91;i] = rest_min_cnt + 1 if rest_min_cnt != -1 else -1\n            \n        \n        return dp&#91;amount]    <\/code><\/pre>\n\n\n\n<p>After many days, I tried the Python solution again to see if it has been internalized by me. Compared with the above, some improvements have been made. I used -1 for all dp list initial values, which means it is impossible at the beginning. dp[0] is set to 0, which means that no coin is taken. The new solution get rid of the rest_min_cnt variable above.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Solution(object):\n    def coinChange(self, coins, amount):\n        \"\"\"\n        :type coins: List&#91;int]\n        :type amount: int\n        :rtype: int\n        \"\"\"\n        dp = &#91;-1] * (amount + 1)\n        dp&#91;0] = 0\n        for i in range(1, amount + 1):\n            for j in coins:\n                k = i - j\n                if k >= 0 and dp&#91;k] != -1:\n                    if dp&#91;i] == -1:\n                        dp&#91;i] = dp&#91;k] + 1\n                    else:\n                        dp&#91;i] = min(dp&#91;i], dp&#91;k] + 1)\n        return dp&#91;amount]<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"http:\/\/feellikelearning.com\/wp-content\/uploads\/2020\/12\/image-25.png\" alt=\"\"\/><\/figure>\n\n\n\n<p>Java version of bottom up dp solution<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Solution {\n    public int coinChange(int&#91;] coins, int amount) {\n        int&#91;] dp = new int&#91;amount + 1];\n        for (int i = 1; i &lt;= amount; i++) {\n            int restMinCoins = -1;\n            for (int coin : coins) {\n                int remainder = i - coin;\n                if (remainder >= 0 &amp;&amp; dp&#91;remainder] != -1) {\n                    if (restMinCoins == -1) {\n                        restMinCoins = dp&#91;remainder];\n                    } else {\n                        restMinCoins = Math.min(restMinCoins, dp&#91;remainder]);\n                    }\n                }\n            }\n            if (restMinCoins == -1) {\n                dp&#91;i] = -1;\n            } else {\n                dp&#91;i] = restMinCoins + 1;\n            }\n        }\n        return dp&#91;amount];\n    }\n}<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Here is the question. I came up with the answer without looking the answer, bottom up dynamic programming (dp) is not a very easy to design at the beginning. Starting from top down + cache, I wrote it a few times, and simplified it a little bit each time, and finally passed the OJ. Python [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":24,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2,7,8,3],"tags":[],"class_list":["post-21","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-algorithms","category-dynamic-programming","category-knapsack","category-leetcode"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v21.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>ALGORITHMS PRACTICE LEETCODE 322 Coin Change - Feel Like Learning<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/feellikelearning.com\/en\/index.php\/2020\/12\/20\/algorithms-practice-leetcode-322-coin-change\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"ALGORITHMS PRACTICE LEETCODE 322 Coin Change - Feel Like Learning\" \/>\n<meta property=\"og:description\" content=\"Here is the question. I came up with the answer without looking the answer, bottom up dynamic programming (dp) is not a very easy to design at the beginning. Starting from top down + cache, I wrote it a few times, and simplified it a little bit each time, and finally passed the OJ. Python [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/feellikelearning.com\/en\/index.php\/2020\/12\/20\/algorithms-practice-leetcode-322-coin-change\/\" \/>\n<meta property=\"og:site_name\" content=\"Feel Like Learning\" \/>\n<meta property=\"article:published_time\" content=\"2020-12-20T20:09:44+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2020-12-20T20:09:45+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/feellikelearning.com\/en\/wp-content\/uploads\/2020\/12\/blog-covers.019-1.jpeg\" \/>\n\t<meta property=\"og:image:width\" content=\"1920\" \/>\n\t<meta property=\"og:image:height\" content=\"1080\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"feellikelearning\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"feellikelearning\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/feellikelearning.com\/en\/index.php\/2020\/12\/20\/algorithms-practice-leetcode-322-coin-change\/\",\"url\":\"https:\/\/feellikelearning.com\/en\/index.php\/2020\/12\/20\/algorithms-practice-leetcode-322-coin-change\/\",\"name\":\"ALGORITHMS PRACTICE LEETCODE 322 Coin Change - Feel Like Learning\",\"isPartOf\":{\"@id\":\"https:\/\/feellikelearning.com\/en\/#website\"},\"datePublished\":\"2020-12-20T20:09:44+00:00\",\"dateModified\":\"2020-12-20T20:09:45+00:00\",\"author\":{\"@id\":\"https:\/\/feellikelearning.com\/en\/#\/schema\/person\/1ec5aac313d6de20215fe2b8e176b8a7\"},\"breadcrumb\":{\"@id\":\"https:\/\/feellikelearning.com\/en\/index.php\/2020\/12\/20\/algorithms-practice-leetcode-322-coin-change\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/feellikelearning.com\/en\/index.php\/2020\/12\/20\/algorithms-practice-leetcode-322-coin-change\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/feellikelearning.com\/en\/index.php\/2020\/12\/20\/algorithms-practice-leetcode-322-coin-change\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/feellikelearning.com\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"ALGORITHMS PRACTICE LEETCODE 322 Coin Change\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/feellikelearning.com\/en\/#website\",\"url\":\"https:\/\/feellikelearning.com\/en\/\",\"name\":\"Feel Like Learning\",\"description\":\"keep curiosity alive\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/feellikelearning.com\/en\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/feellikelearning.com\/en\/#\/schema\/person\/1ec5aac313d6de20215fe2b8e176b8a7\",\"name\":\"feellikelearning\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/feellikelearning.com\/en\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/36aec9d519f02362e3e89b0716ae640d08701f57e818830f3f197db5fbc1ae20?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/36aec9d519f02362e3e89b0716ae640d08701f57e818830f3f197db5fbc1ae20?s=96&d=mm&r=g\",\"caption\":\"feellikelearning\"},\"sameAs\":[\"http:\/\/feellikelearning.com\/en\"],\"url\":\"https:\/\/feellikelearning.com\/en\/index.php\/author\/feellikelearning\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"ALGORITHMS PRACTICE LEETCODE 322 Coin Change - Feel Like Learning","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/feellikelearning.com\/en\/index.php\/2020\/12\/20\/algorithms-practice-leetcode-322-coin-change\/","og_locale":"en_US","og_type":"article","og_title":"ALGORITHMS PRACTICE LEETCODE 322 Coin Change - Feel Like Learning","og_description":"Here is the question. I came up with the answer without looking the answer, bottom up dynamic programming (dp) is not a very easy to design at the beginning. Starting from top down + cache, I wrote it a few times, and simplified it a little bit each time, and finally passed the OJ. Python [&hellip;]","og_url":"https:\/\/feellikelearning.com\/en\/index.php\/2020\/12\/20\/algorithms-practice-leetcode-322-coin-change\/","og_site_name":"Feel Like Learning","article_published_time":"2020-12-20T20:09:44+00:00","article_modified_time":"2020-12-20T20:09:45+00:00","og_image":[{"width":1920,"height":1080,"url":"https:\/\/feellikelearning.com\/en\/wp-content\/uploads\/2020\/12\/blog-covers.019-1.jpeg","type":"image\/jpeg"}],"author":"feellikelearning","twitter_card":"summary_large_image","twitter_misc":{"Written by":"feellikelearning","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/feellikelearning.com\/en\/index.php\/2020\/12\/20\/algorithms-practice-leetcode-322-coin-change\/","url":"https:\/\/feellikelearning.com\/en\/index.php\/2020\/12\/20\/algorithms-practice-leetcode-322-coin-change\/","name":"ALGORITHMS PRACTICE LEETCODE 322 Coin Change - Feel Like Learning","isPartOf":{"@id":"https:\/\/feellikelearning.com\/en\/#website"},"datePublished":"2020-12-20T20:09:44+00:00","dateModified":"2020-12-20T20:09:45+00:00","author":{"@id":"https:\/\/feellikelearning.com\/en\/#\/schema\/person\/1ec5aac313d6de20215fe2b8e176b8a7"},"breadcrumb":{"@id":"https:\/\/feellikelearning.com\/en\/index.php\/2020\/12\/20\/algorithms-practice-leetcode-322-coin-change\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/feellikelearning.com\/en\/index.php\/2020\/12\/20\/algorithms-practice-leetcode-322-coin-change\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/feellikelearning.com\/en\/index.php\/2020\/12\/20\/algorithms-practice-leetcode-322-coin-change\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/feellikelearning.com\/en\/"},{"@type":"ListItem","position":2,"name":"ALGORITHMS PRACTICE LEETCODE 322 Coin Change"}]},{"@type":"WebSite","@id":"https:\/\/feellikelearning.com\/en\/#website","url":"https:\/\/feellikelearning.com\/en\/","name":"Feel Like Learning","description":"keep curiosity alive","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/feellikelearning.com\/en\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/feellikelearning.com\/en\/#\/schema\/person\/1ec5aac313d6de20215fe2b8e176b8a7","name":"feellikelearning","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/feellikelearning.com\/en\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/36aec9d519f02362e3e89b0716ae640d08701f57e818830f3f197db5fbc1ae20?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/36aec9d519f02362e3e89b0716ae640d08701f57e818830f3f197db5fbc1ae20?s=96&d=mm&r=g","caption":"feellikelearning"},"sameAs":["http:\/\/feellikelearning.com\/en"],"url":"https:\/\/feellikelearning.com\/en\/index.php\/author\/feellikelearning\/"}]}},"_links":{"self":[{"href":"https:\/\/feellikelearning.com\/en\/index.php\/wp-json\/wp\/v2\/posts\/21","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/feellikelearning.com\/en\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/feellikelearning.com\/en\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/feellikelearning.com\/en\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/feellikelearning.com\/en\/index.php\/wp-json\/wp\/v2\/comments?post=21"}],"version-history":[{"count":1,"href":"https:\/\/feellikelearning.com\/en\/index.php\/wp-json\/wp\/v2\/posts\/21\/revisions"}],"predecessor-version":[{"id":22,"href":"https:\/\/feellikelearning.com\/en\/index.php\/wp-json\/wp\/v2\/posts\/21\/revisions\/22"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/feellikelearning.com\/en\/index.php\/wp-json\/wp\/v2\/media\/24"}],"wp:attachment":[{"href":"https:\/\/feellikelearning.com\/en\/index.php\/wp-json\/wp\/v2\/media?parent=21"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/feellikelearning.com\/en\/index.php\/wp-json\/wp\/v2\/categories?post=21"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/feellikelearning.com\/en\/index.php\/wp-json\/wp\/v2\/tags?post=21"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}