The trick here is to name the state correctly, then let the implementation follow. For 1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K, the solution in this repository is mainly a greedy solution.
Guide
What?
We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: greedy.
The notes already sitting in the source point us in the right direction:
- Greedy
Guide
When?
This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are findMinFibonacciNumbers.
Guide
Why?
The solution works because it narrows the problem until every update has a clear reason to exist.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Read the setup variables first.
- Follow the main loop or recursive helper next.
- Watch where invalid states get skipped.
- Check which value survives to the return statement.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Greedy
02//Runtime: 4 ms, faster than 80.46% of C++ online submissions for Find the Minimum Number of Fibonacci Numbers Whose Sum Is K.
03//Memory Usage: 6.5 MB, less than 100.00% of C++ online submissions for Find the Minimum Number of Fibonacci Numbers Whose Sum Is K.
04class Solution {
05public:
06 int findMinFibonacciNumbers(int k) {
07 vector<int> fNums = {1, 1};
08 int i;
09
10 while(fNums[fNums.size()-1] < k){
11 fNums.push_back(fNums[fNums.size()-1] + fNums[fNums.size()-2]);
12 }
13
14 // for(int i = 0; i < fNums.size(); i++){
15 // cout << fNums[i] << " ";
16 // }
17 // cout << endl;
18
19 int ans = 0;
20 i = fNums.size()-1;
21
22 while(k > 0){
23 while(i >= 0 && fNums[i] > k){
24 i--;
25 }
26 //the first fibonacci number <= k
27 // cout << i << " " << fNums[i] << " ";
28 k -= fNums[i];
29 ans++;
30 }
31 // cout << endl;
32 // cout << endl;
33
34 return ans;
35 }
36};
Cost