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

翻译

给定一个行数字,生成它的帕斯卡三角形。

例如,给定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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值