Description

Given an integer k, return the minimum number of Fibonacci numbers whose sum is equal to k. The same Fibonacci number can be used multiple times.

The Fibonacci numbers are defined as:

  • F1 = 1
  • F2 = 1
  • Fn = Fn-1 + Fn-2 for n > 2.

It is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to k.

Example 1:

Input: k = 7
Output: 2
Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ...
For k = 7 we can use 2 + 5 = 7.

Example 2:

Input: k = 10
Output: 2
Explanation: For k = 10 we can use 2 + 8 = 10.

Example 3:

Input: k = 19
Output: 3
Explanation: For k = 19 we can use 1 + 5 + 13 = 19.

Constraints:

  • 1 <= k <= 10^9

分析

题目的意思是:给定一个fibonacci数组,求数组中的数和的值等于K的最小数目。这道题我最开始没啥思路,后面发现可以贪心的算法就能够解决,首先找到最大满足K的值,相减,然后剩下的数再从后往前遍历找到最大满足的值,知道相减为0为止,这样就能够找到符合条件的数了,然后求出其长度即为最小长度。

代码

class Solution:
def findMinFibonacciNumbers(self, k: int) -> int:
res=[]
a=1
b=1
res.append(a)
res.append(b)
t=[]
while(a+b<=k):
res.append(a+b)
a,b=b,a+b
n=len(res)
for i in range(n-1,-1,-1):
if(res[i]<k):
k-=res[i]
t.append(res[i])
elif(res[i]==k):
t.append(res[i])
break
return len(t)