Leetcode 322. Coin change-Coin Exchange | Dynamic planning

Source: Internet
Author: User
原题链接:322. Coin Change

"Thinking-java"

The subject examines the dynamic planning. Perhaps at first it was easy to think of greedy algorithm, but the greedy algorithm in some cases is not tenable, such as coins = [1, 3, 5, 6], to amount = 11, with the greedy return 3, actually the least 2 (3 + 5). As a result of dynamic planning, with DP storage number of coins, Dp[i] said that the sum of money I need the minimum number of coins, then the sum of Money amount the minimum number of coins: fixed money for coins[j] a coin, the other amount of money for AMOUNT-COINS[J] its number is Dp[amou Nt-coins[j]],j traverse from 0 to Coins.length-1:

    public int coinchange (int[] coins, int amount) {
        int[] dp = new Int[amount + 1];
        for (int i = 1; I <= amount i++) {
            dp[i] = 0x7fffffff;
            for (int j = 0; J < Coins.length; J +)
                if (i >= coins[j] && dp[i-coins[j]]!= 0x7fffffff)  //①
                    Dp[i] = Math.min (Dp[i], Dp[i-coins[j]] + 1);
        }
        return Dp[amount] = = 0x7fffffff? -1:dp[amount];
    }
180/180 Test cases passed. Runtime:24 ms Your Runtime beats 78.00% of javasubmissions.
Welcome optimization.

"Optimization" by--Kabila, 2016.5.19

Thank you very much enthusiastic Bo Friends Kabila proposed optimization program, its code is as follows:

    public int coinchange (int[] coins, int amount) {
        int[] dp = new Int[amount + 1];
        for (int i = 1; I <= amount i++) dp[i] = 0x7fff_fffe;
        for (int coin:coins)
            for (int i = coin i <= amount i++)
                dp[i] = math.min (dp[i), Dp[i-coin] + 1);
        return Dp[amount] = = 0x7fff_fffe? -1:dp[amount];
    }

180/180 Test cases passed. Runtime:15 ms Your Runtime beats 96.29% of javasubmissions.
The scheme is indeed very ingenious, using 0x7fff_fffe instead of 0x7fff_ffff, while making coins i = coin, so that the original code ① to eliminate the judgment, so as to achieve the optimization effect.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.