Pascal's Triangle Leetcode Java and C++
生活随笔
收集整理的這篇文章主要介紹了
Pascal's Triangle Leetcode Java and C++
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Given?numRows, generate the first?numRows?of Pascal's triangle.
For example, given?numRows?= 5,
Return
?
?
太久沒刷題覺得自己啥也不會了。。。但其實不要有畏難情緒是最重要的,做起來就發現還蠻簡單的。。。 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++還真的挺簡潔的。
轉載于:https://www.cnblogs.com/aprilyang/p/6943158.html
總結
以上是生活随笔為你收集整理的Pascal's Triangle Leetcode Java and C++的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 接口(实例)演示
- 下一篇: 10深入理解C指针之---指针运算和比较