标签:leetcode
问题描述
Given numRows, generate the first numRows of Pascal‘s triangle.
For example, given numRows = 5,
Return
[ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
解决方案
// 使用C++11新特性 class Solution { public: vector<vector<int>> generate( int numRows ) { /* 若numRows小于或等于0,则创建一个空的vector<vector<int>>对象 */ if( numRows <= 0 ) { return { }; } vector<vector<int>> result; // 用来作为结果 vector<int> firstRow = { 1 }; // 杨辉三角的第一行 result.push_back( firstRow ); vector<int> *previousRow = &firstRow; for( int r = 1; r < numRows; ++r ) { vector<int> t = { 1 }; for( int c = 1; c < r; ++c ) { t.push_back( (*previousRow)[c] + (*previousRow)[c - 1] ); } t.push_back( 1 ); result.push_back( t ); previousRow = &(result[r]); } return result; } };
标签:leetcode
原文地址:http://blog.csdn.net/senlinzm/article/details/38981781