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

问题:

求Fibonacci数列中,最少多少个数之和为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-=Fib.back

每次减最大<K的元素。

累计减的次数为res。

代码参考:

 1 class Solution {
 2 public:
 3     int findMinFibonacciNumbers(int k) {
 4         vector<int> Fib={1,1};
 5         int res=0;
 6         while(k>Fib.back()) Fib.push_back(Fib[Fib.size()-1]+Fib[Fib.size()-2]);
 7         while(k){
 8             if(k>=Fib.back()){
 9                 k-=Fib.back();
10                 res++;
11             }
12             Fib.pop_back();
13         }
14         return res;
15     }
16 };
原文地址:https://www.cnblogs.com/habibah-chang/p/13336068.html