118. Pascal's Triangle #1996
Answered
by
mah-shamim
mah-shamim
asked this question in
Q&A
-
Beta Was this translation helpful? Give feedback.
Answered by
mah-shamim
Aug 1, 2025
Replies: 1 comment 2 replies
-
We need to generate the first Approach
Let's implement this solution in PHP: 118. Pascal's Triangle <?php
/**
* @param Integer $numRows
* @return Integer[][]
*/
function generate($numRows) {
$result = array();
if ($numRows <= 0) {
return $result;
}
$result[] = array(1);
for ($i = 1; $i < $numRows; $i++) {
$prevRow = $result[$i - 1];
$currentRow = array();
$currentRow[] = 1;
for ($j = 1; $j < $i; $j++) {
$currentRow[] = $prevRow[$j - 1] + $prevRow[$j];
}
$currentRow[] = 1;
$result[] = $currentRow;
}
return $result;
}
// ----- Example usage -----
// Example 1:
$numRows = 5;
$result = generate($numRows);
// Print result in readable form
echo "Input: numRows = {$numRows}\n";
echo "Output:\n";
print_r($result);
// Example 2:
$numRows = 1;
$result = generate($numRows);
echo "\nInput: numRows = {$numRows}\n";
echo "Output:\n";
print_r($result);
?> Explanation:
This approach efficiently builds each row of Pascal's Triangle by leveraging the properties of the triangle and the values from the previous row, ensuring optimal performance with a time complexity of O(numRows²). |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
topugit
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We need to generate the first
numRows
of Pascal's Triangle. Pascal's Triangle is a triangular array of numbers where each number is the sum of the two numbers directly above it. The solution involves building the triangle row by row, starting from the top.Approach
[1]
.numRows-1
):1
.1
.