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 sizeamount + 1
to store fewest number of coins that need to make up theamount
. - Fill the
dp
array withInteger.MAX_VALUE
, indicating that no perfect square sum has been found. - Set
dp
to0
. - Iterate each coin
i
incoins
:- Use another loop with
j
ranging fromcoins[i]
toamount
:- Update
dp[j]
by taking the minimum of its current value anddp[j - coins[i]] + 1
.
- Update
- Use another loop with
- If
dp[amount]
still equals toInteger.MAX_VALUE
after the iteration, return-1
. Otherwise, returndp[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 sizen + 1
to store the least number of perfect square numbers that sum ton
. - Fill the
dp
array withInteger.MAX_VALUE
, indicating that no perfect square sum has been found. - Set
dp
to0
. - Iterate through a loop with
i
ranging from1
to the integer square root ofn
:- Use another loop with
j
ranging fromi * i
ton
:- Update
dp[j]
by taking the minimum of its current value anddp[j - i * i] + 1
.
- Update
- Use another loop with
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];
}
}