zoukankan      html  css  js  c++  java
  • LeetCode | Pascal's Triangle II

    Given an index k, return the kth row of the Pascal's triangle.

    For example, given k = 3, Return [1,3,3,1].

    Note: Could you optimize your algorithm to use only O(k) extra space?

    按昨天的思路,不考虑空间复杂度的优化:

    //当index=3时,numRows=4
    //额外使用了3个list,题目建议只用一个,运行可以accept
    public class Solution {
        public List<Integer> getRow(int rowIndex) {
            
            List<Integer> result = new ArrayList<Integer>();
            List<Integer> preRow = new ArrayList<Integer>();  
            preRow.add(0);
            
            for(int i=1; i<=rowIndex+1; i++){
                List<Integer> curRow = new ArrayList<Integer>();  
                for(int j=0; j<i; j++){
                    if(j < 1){
                        curRow.add(1);
                    }else if(j >= preRow.size()){
                        curRow.add(1);
                    }else{
                        curRow.add(preRow.get(j-1) + preRow.get(j));
                    }
                }
                preRow = curRow; 
                result = curRow;
            }
            return result;
        }
    }


    优化空间复杂度,只适用一个list:

    //优化空间复杂度:直接在preRow的list上覆写生成curRow,来节省空间
    //思路:row.set(index, Integer) => row.set(j, row.get(j-1)+row.get(j))
    //但是这样的正向遍历是有问题的,本次row.set(j, row[j-1] + row[j]),则下次计算时
    //row.set(j+1, row[j] + row[j+1]),虽然row[j+1]还是preRow中的值,但是row[j]已经被覆写了,
    //而不是preRow的值了,再相加时就不符合杨辉三角了。因而要反向遍历,避免数据污染
    public class Solution {
        public List<Integer> getRow(int rowIndex) {
            
            List<Integer> row = new ArrayList<Integer>();
            row.add(1);
                                                //rowIndex<=0时,跳过循环到return,因而不需额外判断
            for(int i=1; i<=rowIndex; i++){     //i表示index,第1行的index为0
                
                for(int j=row.size()-1; j>0; j--){         //反向遍历填充第i行的[1~~length-1]
                    row.set(j, row.get(j-1)+row.get(j));   //row[0]恒为1,不能覆盖
                }
                row.add(1);                                //在末尾add一个1,构成新row
            }
            
            return row;
        }
    }



  • 相关阅读:
    1052 Linked List Sorting (25 分)
    1051 Pop Sequence (25 分)
    1050 String Subtraction (20 分)
    1049 Counting Ones (30 分)
    1048 Find Coins (25 分)
    1047 Student List for Course (25 分)
    1046 Shortest Distance (20 分)
    1045 Favorite Color Stripe (30 分)
    1044 Shopping in Mars (25 分)
    1055 The World's Richest (25 分)
  • 原文地址:https://www.cnblogs.com/dosmile/p/6444435.html
Copyright © 2011-2022 走看看