0
点赞
收藏
分享

微信扫一扫

Leetcode1414 和为K的最小斐波拉契数字数目(贪心+二分)

追风骚年 2022-02-03 阅读 14

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.

Constraints:

  • 1 <= k <= 10^9

 主要思路:列出所有不大于目标值的斐波拉契数,再逐次用K减去不大于K的最大斐波拉契数,只到K==0,返回减法的次数

class Solution {
public:
    int findMinFibonacciNumbers(int k) {
        vector<int> vfib={1,1};
        for(int i=2;;i++){
            if(vfib[i-1]+vfib[i-2]>k) break;
            vfib.push_back(vfib[i-1]+vfib[i-2]);
        }
        int ans=0;
        while(k>0){
            int maxFib=*(upper_bound(vfib.begin(),vfib.end(),k)-1);
            k-=maxFib;
            ans++;
        }
        return ans;
    }
};

举报

相关推荐

0 条评论