这个和日常数钱一个道理 你肯定是多少张5块的多少张10块的这样来考虑收钱对吧。所以消耗额外的空间少不了了。至于有人用for循环和我用递归其实都一样。至于时间复杂度都最坏就是 o(n)了。
public bool LemonadeChange(int[] bills)
{
if (bills[0] != 5)
return false;
var count5 = 0;
var count10 = 0;
var index = 0;
return _LemonadeChange(bills, count5, count10, index);
}
private bool _LemonadeChange(int[] bills, int count5, int count10, int index)
{
if (index >= bills.Length)
{
return true;
}
else
{
while (index < bills.Length)
{
if (bills[index] == 5)
{
count5++;
index++;
}
else if (bills[index] == 10)
{
if (count5 - 1 < 0) return false;
count5--;
count10++;
index++;
}
else if (bills[index] == 20)
{
if (count10 > 0 && count5 > 0)
{
count5--;
count10--;
index++;
}
else if (count10 <= 0 && count5 - 3 >= 0)
{
count5 = count5 - 3;
index++;
}
else
{
return false;
}
}
}
return _LemonadeChange(bills, count5, count10, index);
}
}
递归没有多余计算还是挺快的,内存也还好。以下仅供参考。。。