问题:
给出数字k,返回总和等于k的最小斐波纳契数,无论是否可以多次使用斐波那契数。
斐波那契数定义为:
F1 = 1
F2 = 1
Fn = Fn-1 + Fn-2 , for n > 2.
保证对于给定的约束,我们总能找到总和为k的斐波那契数。
链接到问题:
https://leetcode.com/problems/find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/
示例: 输入:k = 7 输出2 说明:斐波那契数是:1,1,2,3,5,8,13,... 对于k = 7,我们可以使用2 + 5 = 7。
class Solution {
public int findMinFibonacciNumbers(int count) {
PriorityQueue<Integer> num=new PriorityQueue<>(Collections.reverseOrder());
int i1=1,i2=1;
num.add(i1);
num.add(i2);
int k=count;
int i3=0;
k=k-2;
int res=0;
while(k>=1){
i3=i2+i1;
num.add(i3);
int temp=i2;
i2=i3;
i1=temp;
k--;
}
while(count!=0){
int n=num.poll();
if(n<=count)
{ res++;
count-=n;
}
}
return res;
}
}
它表示“ input = 3”的输出错误。我生成了斐波那契数列,并从最高数遍历,发现小于或等于和的数。如果有人帮助我,那将真的很有帮助。 预先谢谢你。
答案 0 :(得分:3)
您可以简单地使用递归来解决此问题。
这将通过:
class Solution {
public int findMinFibonacciNumbers(int k) {
if (k < 2)
return k;
int first = 1;
int second = 1;
while (second <= k) {
second += first;
first = second - first;
}
return 1 + findMinFibonacciNumbers(k - first);
}
}
我们希望基于标准和约定编写interviews和bug-free代码(例如clean c,1 ,2 c++,1 ,2 java,1 ,2 c#,1 ,2 python ,1 javascript ,1 go ,1 rust )。总体而言,我们希望避免任何可能引起采访争议的事情。
还有其他类似的1,如果您要采访使用该平台的特定公司,您可能必须熟悉它们。