LeetCode 118 Pascal's Triangle(帕斯卡三角形)(vector)

来源:互联网 发布:淘宝女装店铺推荐 编辑:程序博客网 时间:2024/05/16 17:17

翻译

给定一个行数字,生成它的帕斯卡三角形。例如,给定numRows = 5,返回:[     [1],    [1,1],   [1,2,1],  [1,3,3,1], [1,4,6,4,1]]

原文

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]]

分析

这道题可能我写的太不简洁了,不过意思算是表达清楚了。

首先定义pascal,行数小于1的话就直接返回了。

vector<vector<int>> pascal;if (numRows < 1) return pascal;

然后进一步操作,添加一个值为[1]的vector到pascal里,如果行数为1此时就直接返回了。如果不为1就继续执行下一步。

vector<int> root;root.push_back(1);pascal.push_back(root);if (numRows == 1)   return pascal;

看上去和上一步差不多,不过正是借用了上一步中保存的1,这时候root里面已经有两个1了。

root.push_back(1);pascal.push_back(root);if (numRows == 2)   return pascal;

因为我主要是只想操作第n行的中间数字,开头和结尾直接设定成1了。中间部分的话利用上一行的数据来生成就好了。

if (numRows > 2) {        for (int i = 2; i < numRows; ++i) {            vector<int> temp;            temp.push_back(1);            for (int j = 1; j < pascal[i - 1].size(); ++j) {                temp.push_back(pascal[i - 1][j - 1] + pascal[i - 1][j]);            }            temp.push_back(1);            pascal.push_back(temp);        }        return pascal;    }

刚才复制代码的时候发现我没去LeetCode提交,突然有点慌上面直接写的代码会不会有错,结果一提交还对了。

代码

class Solution {public:    vector<vector<int>> generate(int numRows) {        vector<vector<int>> pascal;        if (numRows < 1) return pascal;        vector<int> root;        root.push_back(1);        pascal.push_back(root);        if (numRows == 1)   return pascal;        root.push_back(1);        pascal.push_back(root);        if (numRows == 2)   return pascal;        if (numRows > 2) {            for (int i = 2; i < numRows; ++i) {                vector<int> temp;                temp.push_back(1);                for (int j = 1; j < pascal[i - 1].size(); ++j) {                    temp.push_back(pascal[i - 1][j - 1] + pascal[i - 1][j]);                }                temp.push_back(1);                pascal.push_back(temp);            }            return pascal;        }    }};

Java, updated at 2016/8/26

public class Solution {    public List<List<Integer>> generate(int numRows) {        List<List<Integer>> pascal = new ArrayList<List<Integer>>();        ArrayList<Integer> row = new ArrayList<Integer>();        for (int i = 0; i < numRows; i++) {            row.add(0, 1);            for (int j = 1; j < row.size() - 1; j++)                row.set(j, row.get(j) + row.get(j + 1));            pascal.add(new ArrayList<Integer>(row));        }        return pascal;    }}
1 0
原创粉丝点击