LeetCode | 322. Coin Change, 279. Perfect Squares

322. Coin Change

Link: https://leetcode.com/problems/coin-change/

Description

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

You may assume that you have an infinite number of each kind of coin.

Approach

  • Initialize a dp array of size amount + 1 to store fewest number of coins that need to make up the amount.
  • Fill the dp array with Integer.MAX_VALUE, indicating that no perfect square sum has been found.
  • Set dp to 0.
  • Iterate each coin i in coins:
    • Use another loop with j ranging from coins[i] to amount:
      • Update dp[j] by taking the minimum of its current value and dp[j - coins[i]] + 1.
  • If dp[amount] still equals to Integer.MAX_VALUE after the iteration, return -1. Otherwise, return dp[amount].

Solution

class Solution {
    public int coinChange(int[] coins, int amount) {
        int[] dp = new int[amount + 1];
        Arrays.fill(dp, Integer.MAX_VALUE);
        dp[0] = 0;
        for (int i = 0; i < coins.length; i++) {
            for (int j = coins[i]; j <= amount; j++) {
                if (dp[j - coins[i]] != Integer.MAX_VALUE)
                    dp[j] = Math.min(dp[j], dp[j - coins[i]] + 1);
            }
        }
        return dp[amount] == Integer.MAX_VALUE ? -1 : dp[amount];
    }
}

279. Perfect Squares

Link: https://leetcode.com/problems/perfect-squares/

Description

Given an integer n, return the least number of perfect square numbers that sum to n.

A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.

Approach

  • Initialize a dp array of size n + 1 to store the least number of perfect square numbers that sum to n.
  • Fill the dp array with Integer.MAX_VALUE, indicating that no perfect square sum has been found.
  • Set dp to 0.
  • Iterate through a loop with i ranging from 1 to the integer square root of n:
    • Use another loop with j ranging from i * i to n:
      • Update dp[j] by taking the minimum of its current value and dp[j - i * i] + 1.

Solution

class Solution {
    public int numSquares(int n) {
        int[] dp = new int[n + 1];
        Arrays.fill(dp, Integer.MAX_VALUE);
        dp[0] = 0;
        for (int i = 1; i * i <= n; i++) {
            for (int j = i * i; j <= n; j++) {
                dp[j] = Math.min(dp[j], dp[j - i* i] + 1);
            }
        }
        return dp[n];
    }
}

你可能感兴趣的:(leetcode,算法)