返回

用 C++ 解决 LeetCode 杨辉三角 II 问题:解决方案和算法

IOS

一、概述

杨辉三角是一个特殊的数字三角形,由二项式系数组成。杨辉三角中的数字按行排列,每行数字的个数等于该行数。杨辉三角的第一个数字是 1,然后是 1,1,1,2,1,1,3,3,1,...,以此类推。

二、问题

LeetCode 上的杨辉三角 II 问题如下:

给你一个非负索引 rowIndex,返回「杨辉三角」的第 rowIndex 行。

例如:

  • rowIndex 为 3,输出:[1, 3, 3, 1]
  • rowIndex 为 0,输出:[1]
  • rowIndex 为 1,输出:[1, 1]

三、解决方案

1. 递推法

递推法是一种通过使用之前计算的结果来计算下一个结果的方法。在递推法中,我们首先计算杨辉三角的第一行和第二行。然后,对于接下来的每一行,我们可以使用前一行的数字来计算当前行的数字。

// C++ program to find the nth row of Pascal's Triangle using recursion
#include <iostream>
#include <vector>
using namespace std;

// Function to find the nth row of Pascal's Triangle using recursion
vector<int> getRow(int rowIndex)
{
    // Base cases
    if (rowIndex == 0)
        return {1};
    if (rowIndex == 1)
        return {1, 1};

    // Get the previous row
    vector<int> prevRow = getRow(rowIndex - 1);

    // Create a new vector to store the current row
    vector<int> currentRow(rowIndex + 1, 0);

    // Calculate the current row using the previous row
    for (int i = 1; i < rowIndex; i++)
    {
        currentRow[i] = prevRow[i - 1] + prevRow[i];
    }

    // Return the current row
    return currentRow;
}

int main()
{
    int rowIndex;
    cout << "Enter the index of the row you want to find: ";
    cin >> rowIndex;

    vector<int> row = getRow(rowIndex);

    cout << "The " << rowIndex << "th row of Pascal's Triangle is: ";
    for (int i = 0; i < row.size(); i++)
    {
        cout << row[i] << " ";
    }
    cout << endl;

    return 0;
}

2. 线性递推法

线性递推法是一种改进的递推法,它只需要存储当前行和前一行的数字,就可以计算出下一行的数字。

// C++ program to find the nth row of Pascal's Triangle using linear recursion
#include <iostream>
#include <vector>
using namespace std;

// Function to find the nth row of Pascal's Triangle using linear recursion
vector<int> getRow(int rowIndex)
{
    // Create a vector to store the current row
    vector<int> currentRow(rowIndex + 1, 0);

    // Calculate the first two rows
    currentRow[0] = 1;
    if (rowIndex > 0)
        currentRow[1] = 1;

    // Calculate the remaining rows
    for (int i = 2; i <= rowIndex; i++)
    {
        for (int j = i; j > 0; j--)
        {
            currentRow[j] += currentRow[j - 1];
        }
    }

    // Return the current row
    return currentRow;
}

int main()
{
    int rowIndex;
    cout << "Enter the index of the row you want to find: ";
    cin >> rowIndex;

    vector<int> row = getRow(rowIndex);

    cout << "The " << rowIndex << "th row of Pascal's Triangle is: ";
    for (int i = 0; i < row.size(); i++)
    {
        cout << row[i] << " ";
    }
    cout << endl;

    return 0;
}

四、总结

在本文中,我们讨论了如何使用 C++ 解决 LeetCode 上的杨辉三角 II 问题。我们介绍了递推法和线性递推法这两种解决方案,并提供了详细的代码示例。通过这些代码,您可以轻松理解和实现杨辉三角的算法,并解决此问题。