The purpose of this assignment is to give you practice writing programs with recursion.
Implement a recursive function count()
to compute
\( D(m, n)\) by using the following recurrence relation:
\( \displaystyle D(m, n) \; = \; \begin{cases} \;\; 1 & \text{if } m = 0 \\[.5em] \;\; 1 & \text{if } n = 0 \\[.5em] \;\; D(m-1, n) + D(m-1, n-1) + D(m, n-1) & \text{otherwise} \end{cases} \)
To do so, organize your program according to the following public API:
public class DelannoyBrute { // Returns the Delannoy number D(m, n). public static long count(int m, int n) // Takes two integer command-line arguments m and n and prints D(m, n). public static void main(String[] args) }
As you will see, this approach is hopelessly slow, even for moderately large values of m and n.
~/Desktop/recursion> java-introcs DelannoyBrute 2 2 13 ~/Desktop/recursion> java-introcs DelannoyBrute 3 2 25 ~/Desktop/recursion> java-introcs DelannoyBrute 2 3 25 ~/Desktop/recursion> java-introcs DelannoyBrute 3 3 63 ~/Desktop/recursion> java-introcs DelannoyBrute 20 20 [takes too long]
Note: you may assume that m and n are non-negative integers.
Delannoy numbers arise in combinatorics and computational biology. For example, \(D(m, n)\) is the number of global alignments of two strings of lengths m and n.
DelannoyDP.java
that takes two integer
command-line arguments m and n and computes the Delannoy
number \(D(m, n)\) using dynamic programming.
Hint: use a two-dimensional array with element delannoy[i][j]
storing \(D(i, j)\).
To do so, organize your program according to the following public API:
This version should be fast enough to handle larger values of m and n.public class DelannoyDP { // Returns the Delannoy number D(m, n). public static long count(int m, int n) // Takes two integer command-line arguments m and n and prints D(m, n). public static void main(String[] args) }
~/Desktop/recursion> java-introcs DelannoyDP 2 2 13 ~/Desktop/recursion> java-introcs DelannoyDP 3 2 25 ~/Desktop/recursion> java-introcs DelannoyDP 2 3 25 ~/Desktop/recursion> java-introcs DelannoyDP 3 3 63 ~/Desktop/recursion> java-introcs DelannoyDP 20 20 260543813797441