日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

Pascal's Triangle Leetcode Java and C++

發(fā)布時間:2024/4/14 c/c++ 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Pascal's Triangle Leetcode Java and C++ 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

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

?

?

太久沒刷題覺得自己啥也不會了。。。但其實不要有畏難情緒是最重要的,做起來就發(fā)現(xiàn)還蠻簡單的。。。 public class Solution {public List<List<Integer>> generate(int numRows) {List<List<Integer>> result = new ArrayList<>();if (numRows <= 0) {return result;}for (int i = 0; i < numRows; i++) {List<Integer> array = new ArrayList<>();array.add(1);if (i > 0) {List<Integer> pre = result.get(i - 1);int size = pre.size();for (int j = 0; j < size; j++) {if (j == size - 1) {array.add(pre.get(j));} else {array.add(pre.get(j) + pre.get(j + 1));}}}result.add(array);}return result;} }

看了top solution后的改進版本,減少了條件判斷:

public class Solution {public List<List<Integer>> generate(int numRows) {List<List<Integer>> result = new ArrayList<>();if (numRows <= 0) {return result;}for (int i = 0; i < numRows; i++) {List<Integer> array = new ArrayList<>();for (int j = 0; j < i + 1; j++) {if (j == 0 || j == i) {array.add(1);} else {List<Integer> pre = result.get(i - 1);array.add(pre.get(j - 1) + pre.get(j));}}result.add(array);}return result;} }

?

但看了另一個top solution還是覺得可能自己就是寫不好代碼了。。。= =?

但也許我寫的比較快一點吧?并不好判斷。。。

public class Solution {public List<List<Integer>> generate(int numRows) {List<List<Integer>> result = new ArrayList<>();List<Integer> array = new ArrayList<>();if (numRows <= 0) {return result;}for (int i = 0; i < numRows; i++) {array.add(0, 1);for (int j = 1; j < array.size() - 1; j++) {array.set(j, array.get(j) + array.get(j + 1));}result.add(new ArrayList<>(array));}return result;} }

?附上c++的解法,和第一種解法的改進版是一樣的:

class Solution { public:vector<vector<int>> generate(int numRows) {vector<vector<int>> r(numRows);for (int i = 0; i < numRows; i++) {r[i].resize(i + 1);r[i][0] = 1, r[i][i] = 1;for (int j = 1; j < i; j++) {r[i][j] = r[i - 1][j - 1] + r[i - 1][j];}}return r;} };

?這么一看c++還真的挺簡潔的。

轉(zhuǎn)載于:https://www.cnblogs.com/aprilyang/p/6943158.html

總結(jié)

以上是生活随笔為你收集整理的Pascal's Triangle Leetcode Java and C++的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。