Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- PRACTICA 5 - RECURSIVIDAD MULTIPLE - CON MEMORIA - PASO A ITERATIVO (BOTTOM-UP)
- PROBLEMA 1. Diseñar un algoritmo recursivo, con y sin memoria, y posteriormente encontrar un algoritmo iterativo que calcuile los valores de la recurrencia:
- f(n) = 4*f(n-1) + f(n-2) + f(n-3)
- siendo f(2) = 1, f(1) = 1, f(0) = 2
- 1. Algoritmo Recursivo sin memoria
- 2. Algoritmo Recursivo con memoria
- 3. Algoritmo iterativo (Recursivo final)
- public class Practica5 {
- public static void main(String[] args) {
- System.out.println(fRM(5));
- }
- public static Long fRM(Integer n) {
- Long r;
- if (n == 0){
- r=2L;
- }else if (n==1 || n==2){
- r=1L;
- }else{
- r=4*fRM(n-1) + fRM(n-2) + fRM(n-3);
- }
- return r;
- }
- public static Long fRMM(Integer n) {
- Map<Integer, Long> m = new HashMap<>();
- return fRMM(n,m);
- }
- public static Long fRMM(Integer n, Map<Integer,Long> m) {
- Long r;
- if (m.containsKey(n)){
- r=m.get(n);
- }else {
- if (n==0) {
- r=2L;
- m.put(n, r);
- }else if (n==1 || n==2) {
- r=1L;
- m.put(n, r);
- }else {
- r=4*fRMM(n-1,m)+fRMM(n-2,m)+fRMM(n-3,m);
- m.put(n, r);
- }
- }
- return r;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement