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

    Given the number kreturn the minimum number of Fibonacci numbers whose sum is equal to k, whether a Fibonacci number could 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 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
    class Solution {
        public int findMinFibonacciNumbers(int k) {
            TreeSet<Integer> set = new TreeSet();
            int a = 0, b = 1;
            int c = a + b;
            set.add(1);
            while(c <= k) {
                c = a + b;
                set.add(c);
                a = b;
                b = c;
            }
            int res = 0;        
            while(k > 0) {
                int cur = set.floor(k);
                res++;
                k -= cur;
            }
            return res;
        }
    }

    Fibonacci数的产生要三个变量,记一下

    这题用TreeSet的floor方法,返回离k最近(小于等于)的key,然后继续往下即可.类似的还有ceiling方法,返回大于等于的key

  • 相关阅读:
    Linux的网络配置
    Linux进程
    我需要的电脑配置
    spring注解配置
    spring中集合的配置
    getProperty()方法的参数和用途
    树的遍历
    单词变换
    最短路径dijkstra算法
    文件路径
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13724338.html
Copyright © 2011-2022 走看看