Advertisement
Guest User

Untitled

a guest
Nov 21st, 2017
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. PRACTICA 5 - RECURSIVIDAD MULTIPLE - CON MEMORIA - PASO A ITERATIVO (BOTTOM-UP)
  2.  
  3. PROBLEMA 1. Diseñar un algoritmo recursivo, con y sin memoria, y posteriormente encontrar un algoritmo iterativo que calcuile los valores de la recurrencia:
  4.  
  5. f(n) = 4*f(n-1) + f(n-2) + f(n-3)
  6.  
  7. siendo f(2) = 1, f(1) = 1, f(0) = 2
  8.  
  9. 1. Algoritmo Recursivo sin memoria
  10. 2. Algoritmo Recursivo con memoria
  11. 3. Algoritmo iterativo (Recursivo final)
  12.  
  13.  
  14.  
  15.  
  16.  
  17. public class Practica5 {
  18.  
  19. public static void main(String[] args) {
  20. System.out.println(fRM(5));
  21. }
  22.  
  23. public static Long fRM(Integer n) {
  24. Long r;
  25. if (n == 0){
  26. r=2L;
  27. }else if (n==1 || n==2){
  28. r=1L;
  29. }else{
  30. r=4*fRM(n-1) + fRM(n-2) + fRM(n-3);
  31. }
  32. return r;
  33.  
  34. }
  35.  
  36. public static Long fRMM(Integer n) {
  37. Map<Integer, Long> m = new HashMap<>();
  38. return fRMM(n,m);
  39. }
  40.  
  41. public static Long fRMM(Integer n, Map<Integer,Long> m) {
  42. Long r;
  43. if (m.containsKey(n)){
  44. r=m.get(n);
  45. }else {
  46. if (n==0) {
  47. r=2L;
  48. m.put(n, r);
  49. }else if (n==1 || n==2) {
  50. r=1L;
  51. m.put(n, r);
  52. }else {
  53. r=4*fRMM(n-1,m)+fRMM(n-2,m)+fRMM(n-3,m);
  54. m.put(n, r);
  55. }
  56. }
  57. return r;
  58.  
  59. }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement