Last active
November 14, 2023 23:39
-
-
Save ynechaev/27d969d52bb00ec6b4adc52fbdff4250 to your computer and use it in GitHub Desktop.
The Coin Change Problem - Swift solution (Dynamic programming)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Given an amount and the denominations of coins available, determine how many ways change can be made for amount. | |
There is a limitless supply of each coin type. | |
Example | |
n = 3 | |
c = [8,3,1,2] | |
There are 3 ways to make change for n=3: {1,1,1}, {1,2}, and {3}. | |
*/ | |
func getWays(n: Int, c: [Int]) -> Int { | |
var dp = [Int](repeating: 0, count: n+1) | |
dp[0] = 1 | |
for coin in c { | |
if coin > n { | |
continue | |
} | |
for i in coin...n { | |
dp[i] += dp[i - coin] | |
} | |
} | |
return dp[n] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment