【发布时间】:2022-11-03 11:19:11
【问题描述】:
我正在尝试用下一个基本思想解决leetcode problem:
fun coinChange(coins: IntArray, amount: Int): Int {
fun calc(source: Long, lvl: Int): Int =
if (source == amount.toLong())
lvl
else if (source > amount)
-1
else
coins
.map { calc(source = source + it, lvl = lvl + 1) }
.filter { it > 0 }
.sorted()
.firstOrNull() ?: -1
return calc(source = 0, lvl = 0)
}
这个算法看起来是正确的,但它非常慢并且由于堆栈溢出而无法通过测试。在那种情况下,我试图加快一点速度,但现在它无法正常工作:
fun coinChange(coins: IntArray, amount: Int): Int {
val memoized = mutableMapOf<Int, Int>()
fun calc(source: Int, lvl: Int): Int =
if (source == amount)
lvl
else if (source > amount)
-1
else
memoized.getOrElse(source) {
val evaluated = coins
.reversed()
.map { calc(source = source + it, lvl = lvl + 1) }
.filter { it > 0 }
.minOrNull() ?: -1
memoized[source] = evaluated
evaluated
}
return calc(source = 0, lvl = 0)
}
对于输入coinChange(coins = intArrayOf(186, 419, 83, 408), amount = 6249),它返回36,但必须是20。你会帮助我吗?
【问题讨论】:
-
似乎您的问题与算法有关,因此如果您先解释您的方法,则更容易解决
-
@AbhinavMathur 我的方法是通过源代码描述的。我以声明方式使用经典的“执行树”。
-
对于那些不熟悉 Java/Kotlin 的人来说,这很难读,因为这是一种常见的算法。除非错误的答案是实现的结果,否则算法解释会更好(这只是我的观点,其他人可能会觉得这更容易阅读)
标签: java algorithm kotlin functional-programming