[Greedy] B_5373. The sum of the minimum number of Fibonacci numbers of K (play table)

1. Title Description

To give you the number k, please return the minimum number of Fibonacci numbers that are sum k, where each Fibonacci number can be used multiple times.

Fibonacci numbers are defined as:

  • F1 = 1
    F2 = 1
    Fn = Fn-1 + Fn-2, where n> 2.

The data guarantees that for a given k, a feasible solution must be found.

Tip: 1 <= k <= 10 ^ 9

输入:k = 7
输出:2 
解释:斐波那契数字为:1,1,2,3,5,8,13,……
对于 k = 7 ,我们可以得到 2 + 5 = 7 。

输入:k = 19
输出:3 
解释:对于 k = 19 ,我们可以得到 1 + 5 + 13 = 19 。

Method 1: Greed

The least number required is used, which means that we can only use a relatively large number close to k first. My approach is to pre-process the fab first, and then enumerate from back to front, try to use large numbers.

public int findMinFibonacciNumbers(int k) {
    List<Integer> fab = new ArrayList<>();
    fab.add(1);
    fab.add(1);
    while (fab.get(fab.size()-1) < k) {
        int t = fab.get(fab.size()-1) + fab.get(fab.size()-2); 
        fab.add(t);
    }
    int cnt = 0;
    for (int i = fab.size()-1; i >= 0; i--) {
        while (k >= fab.get(i)) {
            k -= fab.get(i);
            cnt++;
        } 
    }
    return cnt;
}

Complexity analysis

  • time complexity: O ( n ) O (n)
  • Space complexity: O ( n ) O (n)
Published 714 original articles · praised 199 · 50,000+ views

Guess you like

Origin blog.csdn.net/qq_43539599/article/details/105615536