Showing posts with label pascal triangle. Show all posts
Showing posts with label pascal triangle. Show all posts

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:

Pascal's Triangle II

Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return [1,3,3,1].
Note:
Could you optimize your algorithm to use only O(k) extra space?


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> result;
        int n = rowIndex / 2;
        result.push_back(1);
        for(int i = 1; i <= n; i++){
            long long next = (long(result[i - 1]) * long(rowIndex - i  + 1)) / i;
            result.push_back(next);
        }
        if(rowIndex % 2 == 1){
            int size = result.size();
            for(int i = size - 1; i >= 0; i--){
                result.push_back(result[i]);
            }
        }else{
            int size = result.size();
            for(int i = size - 2; i >= 0; i--){
                result.push_back(result[i]);
            }
        }
        return result;
    }
};
Share:

Contact Me

Name

Email *

Message *

Popular Posts