1.C实现
文章来源:https://www.toymoban.com/news/detail-550132.html
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
int** generate(int n, int* rnum_row, int** rnum_row_ele)
{
//*rnum_row-->num_row:杨辉三角行数
*rnum_row = n;
//*rnum_row_ele-->num_row_ele:一级指针 指向一维数组 n个int-->每一行元素个数
*rnum_row_ele = (int*)malloc(sizeof(int) * n);
//a:二级指针 指向一个一维数组 n个int* 每一个int*指向一个一维数组-->存放杨辉三角数据
int** a = (int**)malloc(sizeof(int*) * n);
for (int i = 0; i < n; ++i)
{
//第i行 i+1个数据 *(a + i):一级指针 指向一个一维数组 --> 存放杨辉三角数据
*(a + i) = (int*)malloc(sizeof(int) * (i + 1));
//首尾均为1
a[i][0] = a[i][i] = 1;
//第i行 元素个数i+1
*((*rnum_row_ele) + i) = i + 1;
for (int j = 1; j < i; ++j)
{
a[i][j] = a[i - 1][j] + a[i - 1][j - 1];
}
}
return a;
}
int main()
{
int n = 0; //输出n行杨辉三角的内容
scanf("%d", n);
int num_row = 0; //杨辉三角行数
int* num_row_ele = NULL;//一级指针 指向一个一维数组 存放每一行元素个数
int** arr = generate(n, &num_row, &num_row_ele);
// 输出结果
for (int i = 0; i < num_row; ++i)
{
for (int j = 0; j < *(num_row_ele + i); ++j)
{
printf("%d ", arr[i][j]);
}
printf("\n");
}
// 释放内存
for (int i = 0; i < num_row; ++i)
{
free(arr[i]);
}
free(arr);
free(num_row_ele);
return 0;
}
2.C++实现
文章来源地址https://www.toymoban.com/news/detail-550132.html
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution
{
public:
//Solution类的公有成员函数
vector<vector<int>> generate(int numRows)
{
vector<vector<int>> vv;
vv.resize(numRows);
for (size_t i = 0; i < vv.size(); ++i)
{
//第i行 i+1个数据 初始化0
vv[i].resize(i + 1, 0);
//头尾为1
vv[i].front() = vv[i].back() = 1;
}
for (size_t i = 0; i < vv.size(); ++i)
{
for (size_t j = 0; j < vv[i].size(); ++j)
{
if (vv[i][j] == 0)
vv[i][j] = vv[i - 1][j] + vv[i - 1][j - 1];
}
}
return vv;
}
};
int main()
{
int n = 0;
scanf("%d", n);
Solution s;
vector<vector<int>> ret = s.generate(n);
for (size_t i = 0; i < ret.size(); ++i)
{
for (size_t j = 0; j < ret[i].size(); ++j)
{
cout << ret[i][j] << " ";
}
cout << endl;
}
return 0;
}
到了这里,关于leetcode--杨辉三角(C、C++)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!