Likou 119. Yanghui Triangle II-C Language Implementation

topic

Given a non-negative index k, where k ≤ 33, return the kth row of Yanghui triangle.

Insert picture description here

In the Yanghui triangle, each number is the sum of the numbers on its upper left and upper right.

Example:

Input: 3
Output: [1,3,3,1]

Source: LeetCode
Link: https://leetcode-cn.com/problems/pascals-triangle-ii The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Problem solving

template:

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* getRow(int rowIndex, int* returnSize){
    
    

}

Answer:

The solution to the Yanghui triangle for this question can be obtained directly by the element. For example, the question requires the k-th Yanghui triangle (at least two layers deal with triangles, so the second layer is recorded as 1). For
example, the fourth layer is calculated. , What we need is the third level of numbers to perform an addition operation, so we can recursively to the first level for this, and then perform a violent algorithm, we only need two elements of the previous level to find an element. , But it is a process of constantly pushing to the upper level. So the loop is indispensable. Let's first perform a basic initialization:
1: First of all, for the conversion of the number of layers, the first layer actually has two elements. Is the number of elements in the following levels one more than the number of layers, so We can get:

*returnSize=rowIndex+1;  //层级内的个数修正

What we need to return is the k-th level array, so we need to initialize this array:

int *row=malloc(sizeof(int)*(*returnSize));		
//建立起指针(字节大小为于类型已指出)
memset(row,0,sizeof(int)*(*returnSize));		
//对于这个数组内填充满0
row[0]=1;
//第一个元素始终是1

Based on our analysis above, it is obvious that we have learned how to get the kth layer, which is to advance downwards in order and then we can get it.
Establish a downward cycle according to the number of layers:

for(int i=1;i<=rowIndex;++i){
    
    
}

Satisfy the internal logic of upward advancement:

        for (int j = i; j > 0; --j) {
    
    
           row[j] += row[j - 1];
       }

Finally, comprehensively available: ( Hyperlink to the solution )

int* getRow(int rowIndex, int* returnSize) {
    
    
    *returnSize = rowIndex + 1;
    int* row = malloc(sizeof(int) * (*returnSize));
    memset(row, 0, sizeof(int) * (*returnSize));
    row[0] = 1;
    for (int i = 1; i <= rowIndex; ++i) {
    
    
        for (int j = i; j > 0; --j) {
    
    
            row[j] += row[j - 1];
        }
    }
    return row
}

Guess you like

Origin blog.csdn.net/qq_44922487/article/details/113793218