-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinNumOfFibonaacciWithSumK.java
More file actions
118 lines (96 loc) · 2.99 KB
/
Copy pathMinNumOfFibonaacciWithSumK.java
File metadata and controls
118 lines (96 loc) · 2.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/*
How many minimum numbers from fibonacci series are required such that sum of numbers should be equal to a given Number N?
Note : repetition of number is allowed.
Example:
N = 4
Fibonacci numbers : 1 1 2 3 5 .... so on
here 2 + 2 = 4
so minimum numbers will be 2
*/
public class Solution {
HashMap<String,Integer> map = null;
public int fibsum(int A) {
//map = new HashMap<>();
ArrayList<Integer> fib = new ArrayList<>();
fib.add(1);
fib.add(1);
while(fib.get(fib.size() - 1) < A){
fib.add(fib.get(fib.size()-1) + fib.get(fib.size()-2));
}
return min1(fib,A);
}
// greedy approach -> https://en.wikipedia.org/wiki/Zeckendorf%27s_theorem
/*
if fibonnacci(i) <= N
then 1 + fibonacci(N - fibonacci(i))
else move to lower fibonacci number (i--);
*/
private int min1(ArrayList<Integer> fib,int sum){
int count = 0;
int i = fib.size() - 1;
while(sum > 0){
if(sum >= fib.get(i)){
sum = sum - fib.get(i);
/*
if we have to count unique number then declare HashSet and keeping adding numbers to set
finally return size of set or in case of numbers set
*/
count++;
}
else{
i--;
}
}
return count;
}
//dp
private int min2(ArrayList<Integer> fib,int sum){
int dp[][] = new int[fib.size()+1][sum+1];
for(int i=0; i<=fib.size(); i++){
dp[i][0] = 0;
}
for(int j=1; j<=sum; j++){
dp[0][j] = Integer.MAX_VALUE - 1;
}
for(int i=1; i<=fib.size(); i++){
for(int j=1; j<=sum; j++){
if(fib.get(i-1) <= j){
dp[i][j] = Math.min(1 + dp[i][j - fib.get(i-1)], dp[i-1][j]);
}
else{
dp[i][j] = dp[i-1][j];
}
}
}
return dp[fib.size()][sum];
}
private int min3(int i,ArrayList<Integer> fib,int sum){
String key = i + "|" + sum;
if(map.containsKey(key)){
return map.get(key);
}
if(sum == 0){
map.put(key,0);
return 0;
}
if(i == fib.size()){
return Integer.MAX_VALUE;
}
int min = Integer.MAX_VALUE;
if(fib.get(i) <= sum){
int a = min3(i,fib,sum - fib.get(i));
if(a != Integer.MAX_VALUE){
a = a + 1;
}
int b = min3(i+1,fib,sum);
if(a == Integer.MAX_VALUE && b == Integer.MAX_VALUE){
//do nothing
}
else{
min = Math.min(a,b);
}
}
map.put(key,min);
return min;
}
}