Algorithm 这是正确的重复关系I';你为硬币兑换挑战找到了什么?
我试图解决“硬币兑换问题”,我想我已经想出了一个递归的解决方案,但我想验证一下 作为一个例子,让我们假设我们有便士、五分镍币和一角镍币,并试图用22美分兑换Algorithm 这是正确的重复关系I';你为硬币兑换挑战找到了什么?,algorithm,recursion,data-structures,tree,time-complexity,Algorithm,Recursion,Data Structures,Tree,Time Complexity,我试图解决“硬币兑换问题”,我想我已经想出了一个递归的解决方案,但我想验证一下 作为一个例子,让我们假设我们有便士、五分镍币和一角镍币,并试图用22美分兑换 C = { 1 = penny, nickle = 5, dime = 10 } K = 22 那么做出改变的方法有很多 f(C,N) = f({1,5,10},22) = (# of ways to make change with 0 dimes) + (# of ways to make change with 1 dim
C = { 1 = penny, nickle = 5, dime = 10 }
K = 22
那么做出改变的方法有很多
f(C,N) = f({1,5,10},22)
=
(# of ways to make change with 0 dimes)
+ (# of ways to make change with 1 dimes)
+ (# of ways to make change with 2 dimes)
= f(C\{dime},22-0*10) + f(C\{dime},22-1*10) + f(C\{dime},22-2*10)
= f({1,5},22) + f({1,5},12) + f({1,5},2)
及
等等
换句话说,我的算法是
let f(C,K) be the number of ways to make change for K cents with coins C
and have the following implementation
if(C is empty or K=0)
return 0
sum = 0
m = C.PopLargest()
A = {0, 1, ..., K / m}
for(i in A)
sum += f(C,K-i*m)
return sum
如果有任何缺陷呢
我想是线性时间 重新思考您的基本案例:
1. What if K < 0 ? Then no solution exists. i.e. No of ways = 0.
2. When K = 0, so there is 1 way to make changes and which is to consider zero elements from array of coin-types.
3. When coin array is empty then No of ways = 0.
这将是N(数组大小)的指数形式
如果您希望改进,我建议您使用动态规划。我的回答对您有帮助吗?
1. What if K < 0 ? Then no solution exists. i.e. No of ways = 0.
2. When K = 0, so there is 1 way to make changes and which is to consider zero elements from array of coin-types.
3. When coin array is empty then No of ways = 0.
T(N) = O(N) + K*T(N-1)