Monday 25 July 2016

Pascal's Triangle

Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
 * Return an array of arrays.
 * The sizes of the arrays are returned as *columnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
 int** generate(int numRows, int** columnSizes) {
    if(numRows == 0)
        return NULL;
    int **result = (int **)malloc(numRows * sizeof(int *));
    
    (*columnSizes) = (int *)malloc(numRows * sizeof(int));

    int i, j;
    for (i = 0; i < numRows; i++) {
        (*columnSizes)[i] = i + 1;
        result[i] = (int *)malloc((*columnSizes)[i] * sizeof(int));
        result[i][0] = 1;
        for (j = 1; j < i; j++) {
            result[i][j] = result[i - 1][j - 1] + result[i - 1][j];
        }
        result[i][i] = 1;
    }
    return result;
}
Share:

0 comments:

Post a Comment

Contact Me

Name

Email *

Message *

Popular Posts

Blog Archive