To represent a number as the sum of the minimum number of Fibonacci numbers, always subtract the largest Fibonacci number less than or equal to the current value. This is based on Zeckendorf’s theorem, which states every positive integer can be uniquely represented as the sum of non-consecutive Fibonacci numbers.
classSolution {
publicintfindMinFibonacciNumbers(int k) {
List<Integer> fib =new ArrayList<>();
fib.add(1); fib.add(1);
while(fib.get(fib.size()-1) < k) fib.add(fib.get(fib.size()-1) + fib.get(fib.size()-2));
int ans = 0;
for(int i = fib.size()-1; i >= 0 && k > 0; --i) {
if(fib.get(i) <= k) {
k -= fib.get(i);
ans++;
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
funfindMinFibonacciNumbers(k: Int): Int {
val fib = mutableListOf(1, 1)
while (fib.last() < k) fib.add(fib.last() + fib[fib.size-2])
var ans = 0var kk = k
for (i in fib.size-1 downTo 0) {
if (fib[i] <= kk) {
kk -= fib[i]
ans++ }
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
deffindMinFibonacciNumbers(self, k: int) -> int:
fib = [1, 1]
while fib[-1] < k:
fib.append(fib[-1] + fib[-2])
ans =0for f in reversed(fib):
if f <= k:
k -= f
ans +=1return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfnfind_min_fibonacci_numbers(mut k: i32) -> i32 {
letmut fib =vec![1, 1];
while*fib.last().unwrap() < k {
let n = fib.len();
fib.push(fib[n-1] + fib[n-2]);
}
letmut ans =0;
for&f in fib.iter().rev() {
if f <= k {
k -= f;
ans +=1;
}
}
ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
findMinFibonacciNumbers(k: number):number {
constfib= [1, 1];
while (fib[fib.length-1] <k) fib.push(fib[fib.length-1] +fib[fib.length-2]);
letans=0;
for (leti=fib.length-1; i>=0&&k>0; --i) {
if (fib[i] <=k) {
k-=fib[i];
ans++;
}
}
returnans;
}
}