zoukankan      html  css  js  c++  java
  • [LeetCode] 1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K

    Given an integer kreturn 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

    和为 K 的最少斐波那契数字数目。

    给你数字 k ,请你返回和为 k 的斐波那契数字的最少数目,其中,每个斐波那契数字都可以被使用多次。

    斐波那契数字定义为:

    F1 = 1
    F2 = 1
    Fn = Fn-1 + Fn-2 , 其中 n > 2 。
    数据保证对于给定的 k ,一定能找到可行解。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    思路是递归/贪心。对于一个数字K,我们一开始并不确定他到底是不是属于斐波那契数列的一部分,但是根据例子我们可以这样做,如果K正好是斐波那契数列的某一个数字,那么直接就返回1;如果K不是斐波那契数列的某一个数字,那么我们为了尽量减少组成K的数字的数目,我们可以对K减去比K小的最大的斐波那契数。我们按照这个思路一直递归下去,直到K == 0。

    时间O(K)

    空间O(K)

    Java实现

     1 class Solution {
     2     public int findMinFibonacciNumbers(int k) {
     3         int count = 1;
     4         // base case
     5         if (k == 0) {
     6             return 0;
     7         }
     8         
     9         // normal case
    10         int first = 1;
    11         int second = 1;
    12         int cur = first + second;
    13         while (cur <= k) {
    14             first = second;
    15             second = cur;
    16             cur = first + second;
    17         }
    18         
    19         // 如果K不在F数列中,则将其减去一个最大的F数
    20         if (second == k) {
    21             return count;
    22         } else {
    23             int res = k - second;
    24             return 1 + findMinFibonacciNumbers(res);
    25         }
    26     }
    27 }

    LeetCode 题目总结

  • 相关阅读:
    sipp如何避免dead call
    6174问题
    笨小熊
    scanf 与 cin 的区别
    谁获得了最高奖学金
    _int64、long long 的区别
    小光棍数
    简单排序法
    La=LaULb (循环链表)
    删除重复的数(顺序有序表)
  • 原文地址:https://www.cnblogs.com/cnoodle/p/14389251.html
Copyright © 2011-2022 走看看