【LeetCode】6.Array and String — Pascal's Triangle 杨辉三角
作者:互联网
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 5 Output: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
很基础的题目,大学刚开始学C语言或者C++的时候,都会练习的一道题。主要收获就是对二维动态数组有了更多的了解。
方法:定义滑动标签,用于所需计算层的上一层数据获取,来计算 当前层的值。
class Solution { public: vector<vector<int>> generate(int numRows) { if (numRows < 1) return{}; if (numRows == 1) return{ {1} }; if (numRows == 2) return{ {1},{1,1} }; vector<vector<int>> result(numRows); result[0].push_back(1); result[1].push_back(1); result[1].push_back(1); int counter=2; while (counter < numRows) { int tag1 = 0, tag2 = 1; result[counter].push_back(1); while (1) { result[counter].push_back(result[counter - 1][tag1] + result[counter - 1][tag2]); tag1++; tag2++; if (tag2 >=result[counter-1].size()) { result[counter].push_back(1); break; } } counter++; } return result; } };
标签:Triangle,String,tag2,counter,back,numRows,push,result,杨辉三角 来源: https://www.cnblogs.com/hu-19941213/p/10941861.html