2020年5月7日 星期四

[LeetCode] 118. Pascal's Triangle* 解題思路 (Easy)



這題需要組成一個三角形的數字。




LeetCode 題目連結

 

https://leetcode.com/problems/pascals-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]
]

Accept 作法


這題時間複雜度為 O(n2)。n 是 numRows。


Runtime: 0 ms
Memory: 37.3 MB

Java 程式碼

  1. class Solution {
  2. public List<List<Integer>> generate(int numRows) {
  3. List<List<Integer>> result =new ArrayList<>();
  4. if(numRows ==0){
  5. return result;
  6. }
  7. result.add(new ArrayList<>());
  8. result.get(0).add(1);
  9. for(int i = 1;i< numRows;i++){
  10. ArrayList<Integer> list = new ArrayList<Integer>();
  11. List<Integer> lastList = result.get(i-1);
  12. list.add(1);
  13. for(int j = 1;j<i;j++){
  14. int num = lastList.get(j-1)+lastList.get(j);
  15. list.add(num);
  16. }
  17. list.add(1);
  18. result.add(list);
  19. }
  20. return result;
  21. }
  22. }

 

更多 LeetCode 相關資源

 

複習程式面試書籍


除了 LeetCode 練習外,我也入手了這本,題庫來自真正的面試,並非摘自教科書。它們反映出頂尖公司真正會出的題目,你可以藉此做好充分準備
需要的話可以看看,寫得很仔細。


書名:提升程式設計師的面試力:189道面試題目與解答



相關 LeetCode文章一律會放在 程式解題 標籤分類,歡迎持續追蹤。


沒有留言:

張貼留言