Two ways to solve the Fibonacci sequence: Basic recursive vs dynamic programming

Source: Internet
Author: User

/* Basic solution, according to the recursive method, the algorithm's operation time is exponentially increased * This algorithm for similar sub-problems are repeated calculations, and therefore not an efficient algorithm */public class Fibonaccirecursion {//----------- Computes the recursive function of the Fibonacci sequence value--------------public static int fib (int n) {if (n==1| | n==2) {//1th in sequence, 2 digits 1return 1;} return fib (n-1) +fib (n-2);} public static void Main (string[] args) {int i=6; System.out.println ("Fib (" +i+ "):" +fib (i));}}

/* * You can avoid repeated calculations by saving the solution of the calculated sub-problem * that is, using dynamic programming techniques */public class FIBONACCIDP {//----------using Dynamic planning (DP) The value of the Fibonacci sequence is------------public static int fib (int n) {int[] array = new int[n];//used to hold the state in the dynamic planning process array[0] = 1;array[1] = 1 ; for (int i = 2; i < n; i++) array[i] = Array[i-1] + array[i-2];//dynamically planned state-shifted return array[n-1];} public static void Main (string[] args) {System.out.println ("fib (6):" +fib (6));}}

Two ways to solve the Fibonacci sequence: Basic recursive vs dynamic programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.