Skip to content

Instantly share code, notes, and snippets.

@ynechaev
Last active November 14, 2023 23:39
Show Gist options
  • Save ynechaev/27d969d52bb00ec6b4adc52fbdff4250 to your computer and use it in GitHub Desktop.
Save ynechaev/27d969d52bb00ec6b4adc52fbdff4250 to your computer and use it in GitHub Desktop.
The Coin Change Problem - Swift solution (Dynamic programming)
/*
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