LeetCode //C - 119. Pascal‘s Triangle II

119. Pascal’s Triangle II

Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal’s triangle.

In Pascal’s triangle, each number is the sum of the two numbers directly above it as shown:
在这里插入图片描述
 

Example 1:

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

Example 2:

Input: rowIndex = 0
Output: [1]

Example 3:

Input: rowIndex = 1
Output: [1,1]

Constraints:
  • 0 <= rowIndex <= 33

From: LeetCode
Link: 119. Pascal’s Triangle II


Solution:

Ideas:

1. Memory Allocation: The function uses malloc to allocate memory for the array that will store the rowIndex-th row. The size of the array is rowIndex + 1.

2. Initialization: The first element of each row is always 1, so row[0] = 1.

3. Calculating Row Elements:

  • The outer loop runs from 1 to rowIndex to construct each row up to the desired rowIndex.
  • Inside the outer loop, the last element of each row is set to 1.
  • The inner loop updates the elements of the row in reverse order (from right to left) to avoid overwriting the values needed for the calculations. Each element row[j] is updated as the sum of row[j] and row[j-1].

4. Returning the Result: The function returns the pointer to the array containing the desired row.

Code:
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* getRow(int rowIndex, int* returnSize) {
    *returnSize = rowIndex + 1;
    int* row = (int*)malloc((*returnSize) * sizeof(int));
    
    row[0] = 1;  // The first element is always 1

    for (int i = 1; i <= rowIndex; i++) {
        row[i] = 1;  // The last element in each row is always 1
        for (int j = i - 1; j > 0; j--) {
            row[j] = row[j] + row[j - 1];
        }
    }

    return row;
}
  • 14
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Navigator_Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值