1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K

Given the number kreturn the minimum number of Fibonacci numbers whose sum is equal to k, whether a Fibonacci number could 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 k.

给一个k,求问最少用多少个fibonacci数可以组成这个k。

贪心来做,每次找到一个<=k的最大的fibonacci数,减去它继续这个过程,最后得到最小次数。

1.f[i + 2] = f[i] + f[i + 1] 两个相邻的fibonacci肯定能用一个更大的来代替, 减少次数。

2.f[i] * 2 = f[i - 2] + f[i + 1] 一个数的两倍可以等于换成一个大的一个小的之和,因此次数不变。

3.f[0] + f[2] + ... + f[2n] = f[2n+1] - 1

f[1] + f[3] + ... + f[2n-1] = f[2n] - 1 如果k>= f[2n] 又不选 f[2n]的话,那么其他的数的和会小于f[2n],那么你就需要额外多出元素来凑,同理f[2n+1]

从这3条可以看出每次选<=k的最大的fibonacci数的正确的。

class Solution(object):
    def findMinFibonacciNumbers(self, k):
        """
        :type k: int
        :rtype: int
        """
        f1 = f2 = 1
        while f2 <= k:
            f2,f1 = f2 + f1, f2
        ans = 0
        while f1 > 0:
            if k >= f2:
                k -= f2
                ans += 1
            f2, f1 = f1, f2 - f1
        return ans

 

posted @ 2020-07-22 13:01  whatyouthink  阅读(159)  评论(0编辑  收藏  举报