How to use Dynamic Programming In PHP
Dynamic programming can be employed to optimize the calculation of binomial coefficients and improve the overall efficiency of Pascal’s Triangle generation.
PHP
<?php function pascalsTriangle( $rows ) { $triangle = array (); for ( $i = 0; $i < $rows ; $i ++) { $triangle [ $i ] = array (1); for ( $j = 1; $j < $i ; $j ++) { $triangle [ $i ][ $j ] = $triangle [ $i - 1][ $j - 1] + $triangle [ $i - 1][ $j ]; } if ( $i != 0) { $triangle [ $i ][ $i ] = 1; } } // Display the Triangle foreach ( $triangle as $row ) { echo implode( " " , $row ) . "\n" ; } } // Driver code $rows = 5; pascalsTriangle( $rows ); ?> |
Output
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
PHP Program to Print Pascal’s Triangle
Pascal’s Triangle is a mathematical construct named after the French mathematician Blaise Pascal. It is a triangular array of binomial coefficients, where each number is the sum of the two directly above it. In this article, we will explore different approaches to print Pascal’s Triangle in PHP.
Table of Content
- Using Simple Loop
- Using Recursion
- Using Dynamic Programming