Pizza pieces
Description
In her trip to Italy, Elizabeth Gilbert made it her duty to eat perfect pizza. One day, she ordered one for dinner. And then some Italian friends appeared at her room.
The problem is that there were many people who ask for a piece of pizza at that moment. And she had a knife that only cuts straight.
Given a number K
(K<=45000), help her get the maximum of pieces possible (not necessarily of equal size) with K
cuts. If K
is a negative number, the result must be -1
(or Nothing
in Haskell).
Examples
maxPizza(0) == 1
maxPizza(1) == 2
maxPizza(3) == 7
4刀,可以分成11块
是11块,
这个数有规律:
一刀也不切,切0刀:还是1快
切1刀:1+1=2块
切2刀:2+2=4
切3刀:3+4=7
切4刀:4+7=11
切5刀:5+11=16
当前下刀能切成的块数=现在是第几刀的数+前一刀已经切成的块数
公式:Xn=(n+1)*n/2+1,Xn是切成的块数,n是切割的次数.
使用递归处理,需要注意使用尾递归
顾名思义,尾递归就是从最后开始计算, 每递归一次就算出相应的结果, 也就是说, 函数调用出现在调用者函数的尾部, 因为是尾部, 所以根本没有必要去保存任何局部变量. 直接让被调用的函数返回时越过调用者, 返回到调用者的调用者去。尾递归就是把当前的运算结果(或路径)放在参数里传给下层函数,深层函数所面对的不是越来越简单的问题,而是越来越复杂的问题,因为参数里带有前面若干步的运算路径。
尾递归是极其重要的,不用尾递归,函数的堆栈耗用难以估量,需要保存很多中间函数的堆栈。比如f(n, sum) = f(n-1) + value(n) + sum; 会保存n个函数调用堆栈,而使用尾递归f(n, sum) = f(n-1, sum+value(n)); 这样则只保留后一个函数堆栈即可,之前的可优化删去。
public class Pizza
{ public static int maxPizza(int cut) {
//TODO : Code goes here
if (cut < )
{
return -;
}
else if (cut == )
{
return ;
}
else
{
return maxPizza(cut - ) + cut;
}
}
}
其他人的解法:
使用for循环的,当然了这个for循环可以使用Linq来简化
return cut < ? - : Enumerable.Range(, cut).Aggregate(, (x, y) => x + y);
public class Pizza
{ public static int maxPizza(int cut) { if(cut < )
{
return -;
} if(cut == )
{
return ;
} int result = ; for(int i = ; i <= cut; i++)
{
result = result + i;
} return result + ;
}
}