1.递归
结果超时
2.数学法
可以知道结果在shorter*k---longer*k之间
首先判断k是否为0,k为0则返回
其次判断shorter与longer是否相同,若相同,则只有一个结果,返回shorter*k
上述两个都不成立:
则最终的情况是:结果中有0个longer,1个longer,......k个longer
令count=shorter*k,然后遍历1---k,每次令counter的值更新为count-shorter+longer
代码如下:
扫描二维码关注公众号,回复:
10077732 查看本文章
class Solution {
vector<int> res;
public:
vector<int> divingBoard(int shorter, int longer, int k) {
if(k==0)
return res;
if(shorter==longer)
{
res.push_back(shorter*k);//长短相同时,只有一种结果
return res;
}
int count=shorter*k;//对应0个long
res.push_back(count);
for(int i=1;i<=k;i++)
{
count=count-shorter+longer;//分别对应1到K个long
res.push_back(count);
}
return res;
}
};