add new solutions
This commit is contained in:
parent
9c2c959a9b
commit
9a10695e8c
29 changed files with 1074 additions and 2 deletions
31
solutions/3/q322/solution.go
Normal file
31
solutions/3/q322/solution.go
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
package q322
|
||||
|
||||
// Note: The cache size only needs to be min(max(coins), amount).
|
||||
|
||||
func coinChange(coins []int, amount int) int {
|
||||
if amount == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
cache := make([]int, amount+1)
|
||||
cache[0] = amount + 1
|
||||
for p := 1; p < len(cache); p *= 2 {
|
||||
copy(cache[p:], cache[:p]) // fill with MAX+1
|
||||
}
|
||||
cache[0] = 0
|
||||
|
||||
for i := 1; i < len(cache); i++ {
|
||||
for _, c := range coins {
|
||||
if (i - c) < 0 {
|
||||
continue
|
||||
}
|
||||
cache[i] = min(cache[i], cache[i-c]+1)
|
||||
}
|
||||
}
|
||||
if cache[amount] > amount {
|
||||
return -1
|
||||
}
|
||||
return cache[amount]
|
||||
}
|
||||
|
||||
var _ = coinChange
|
||||
Loading…
Add table
Add a link
Reference in a new issue