Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Arrays

Pascal's Triangle Rows

Easy · Arrays · Asked at Amazon, Microsoft, Apple, TCS, Infosys

Print the first n rows of Pascal’s triangle. Row 1 is 1, and every number inside a row is the sum of the two numbers above it.

Input

A single integer n.

Output

n lines — the rows, numbers separated by spaces.

Constraints

Build each row from the previous one: it starts and ends with 1, and row[j] = prev[j − 1] + prev[j] in between. The largest value for n = 30 is about 7.8 × 10^7.

Example 1

Input

5

Output

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

Example 2

Input

1

Output

1

Hints

  1. Every row starts and ends with 1.
  2. Each inner number is the sum of the two numbers above it.

Approach

Start with row [1]. To build the next row, put 1 at both ends and prev[j − 1] + prev[j] in between. Print each row as you go. For n ≤ 30 every value fits in a 32-bit integer (the largest is C(29, 14) ≈ 7.8 × 10^7), but 64-bit is a safe habit.

Complexity: O(n²) time · O(n) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<long long> row = {1};
    for (int i = 0; i < n; i++) {
        for (size_t j = 0; j < row.size(); j++) cout << row[j] << (j + 1 < row.size() ? ' ' : '\n');
        vector<long long> next(row.size() + 1, 1);
        for (size_t j = 1; j < row.size(); j++) next[j] = row[j - 1] + row[j];
        row = next;
    }
    return 0;
}

Python solution

n = int(input())
row = [1]
for _ in range(n):
    print(*row)
    row = [1] + [row[j - 1] + row[j] for j in range(1, len(row))] + [1]

Java solution

import java.util.*;

public class Main {
    public static void main(String[] args) {
        int n = new Scanner(System.in).nextInt();
        long[] row = {1};
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < row.length; j++) sb.append(row[j]).append(j + 1 < row.length ? " " : "\n");
            long[] next = new long[row.length + 1];
            next[0] = next[row.length] = 1;
            for (int j = 1; j < row.length; j++) next[j] = row[j - 1] + row[j];
            row = next;
        }
        System.out.print(sb);
    }
}

Solve Pascal's Triangle Rows online · All practice problems