1.C实现
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>int** generate(int n, int* rnum_row, int** rnum_row_ele)
{*rnum_row = n;*rnum_row_ele = (int*)malloc(sizeof(int) * n);int** a = (int**)malloc(sizeof(int*) * n);for (int i = 0; i < n; ++i){*(a + i) = (int*)malloc(sizeof(int) * (i + 1));a[i][0] = a[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; 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++实现
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution
{
public:vector<vector<int>> generate(int numRows){vector<vector<int>> vv;vv.resize(numRows);for (size_t i = 0; i < vv.size(); ++i){vv[i].resize(i + 1, 0);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;
}