鱼C论坛

 找回密码
 立即注册
查看: 1445|回复: 0

[学习笔记] leetcode 119. Pascal's Triangle II

[复制链接]
发表于 2019-9-29 10:25:09 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.

  2. Note that the row index starts from 0.


  3. In Pascal's triangle, each number is the sum of the two numbers directly above it.

  4. Example:

  5. Input: 3
  6. Output: [1,3,3,1]
  7. Follow up:

  8. Could you optimize your algorithm to use only O(k) extra space?
复制代码

  1. class Solution {
  2.     public List<Integer> getRow(int rowIndex) {
  3.         
  4.         List <Integer> array = new ArrayList<>();
  5.         array.add(1);
  6.         if(rowIndex == 0) return array;
  7.         List <List<Integer>> re = new ArrayList<>();
  8.         re.add(array);
  9.         
  10.         for(int i = 1; i <= rowIndex; i++){
  11.             
  12.             List<Integer> pre = re.get(i-1);
  13.             List<Integer> cur = new ArrayList<>();
  14.             cur.add(1);
  15.             
  16.             for(int j = 1; j < i ; j++){
  17.                
  18.                 cur.add(pre.get(j) + pre.get(j-1));
  19.             }
  20.             
  21.             cur.add(1);
  22.             re.add(cur);
  23.         }
  24.         
  25.         return re.get(re.size()-1);
  26.     }
  27. }
复制代码


optimized with constant space

  1. class Solution {
  2.     public List<Integer> getRow(int rowIndex) {
  3.         
  4.         ArrayList <Integer> array = new ArrayList<>();
  5.         array.add(1);
  6.         if(rowIndex == 0) return array;
  7.         ArrayList<Integer> cur = new ArrayList<>();;
  8.         
  9.         for(int i = 1; i <= rowIndex; i++){
  10.             cur.clear();
  11.             cur.add(1);
  12.             
  13.             for(int j = 1; j < i ; j++){
  14.                
  15.                 cur.add(array.get(j) + array.get(j-1));
  16.             }
  17.             
  18.             cur.add(1);
  19.             array.clear();
  20.             array = (ArrayList<Integer>) cur.clone();
  21.         }
  22.         
  23.         return cur;
  24.     }
  25. }
复制代码

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-2 01:10

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表