2016年2月13日 星期六

LEET code -- 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?

我本來還想找規律
但是這根本沒辦法找規律
因為這一定要用之前算好的累積

所以可以只用一個陣列 但是存的時候是倒過來
因為夏禕牌都比上一排多一個   所以可以不蓋過需要的element




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* getRow(int rowIndex, int* returnSize) {
    //store the element in the tail, to save the space
    if(rowIndex<0)return NULL;
    *returnSize=rowIndex+1;
    int *ans=malloc(sizeof(int)*(rowIndex+1));
    for(int i=0;i<=rowIndex;i++){
        for(int j=i;j>=0;j--){
            if(j==0 || j==i) ans[j]=1;
            else{
                ans[j]=ans[j]+ans[j-1];
            }
        }
    }
    return ans;
}

沒有留言:

張貼留言