我正在做一个来自HackerRank硬币找零问题的练习面试题。
我卡住了,正试图理解这个问题的一个解决方案。 这是该问题的递归解决方案(带有我的评论以便理解它)。
public static int numWays(int[] coins, int sumTo) {
return numWaysWhichCoin(coins, sumTo, 0);
}
private static int numWaysWhichCoin(int[] coins, int sumTo, int whichCoin) {
if(sumTo == 0) {
//empty set
return 1;
} else if(sumTo < 0) {
//no way to form a negative sum with positive coin values
return 0;
} else {
//sumTo is positive
//case gone through all the coins but still a positive sum. Impossible
if(sumTo > 0 && whichCoin == coins.length) {
return 0;
}
//with and without. With, you can keep using the same coin
return numWaysWhichCoin(coins, sumTo - coins[whichCoin], whichCoin) + numWaysWhichCoin(coins, sumTo, whichCoin + 1);
}
}
作者指出该算法的时间复杂度为O(2n)。根据我的面试经验,您应该对答案进行证明。如何证明这种时间复杂度呢?在我之前的工作中,为了证明算法运行时间为O(2n),我会使用递归关系,例如(斐波那契数列)T(n) = T(n-1) + T(n-2) +c <= 2T(n-1) + c, T(1) = d,但是我无法从这里推导出这样的递归关系。有没有其他方法证明呢?