美文网首页
【leetcode】No.118&No.119:pascals-

【leetcode】No.118&No.119:pascals-

作者: I讨厌鬼I | 来源:发表于2019-07-27 18:02 被阅读0次

    题目描述

    Given an index k, return the k th 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?

    思路

    使用dp的思想,每一层的数据都来自上一层的相邻数相加,设dp[i][j]表示第i层第j个数据,递推关系为dp[i][j] = dp[i-1][j-1] + dp[i-1][j],可以看出每一层都只与上一层数据有关,由后往前更新数据的话可以减少空间复杂度。递推关系为dp[j] = dp[j] + dp[j-1]

    代码

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.stream.Collectors;
    
    public class Solution {
        public ArrayList<Integer> getRow(int rowIndex) {
            ArrayList<Integer> res = new ArrayList<>();
            int[] dp = new int[rowIndex + 1];
            dp[0] = 1;
            for (int i=1; i<=rowIndex; i++){
                for (int j=i; j>=1; j--){
                    dp[j] += dp[j-1];
                }
            }
            res.addAll(Arrays.stream(dp).boxed().collect(Collectors.toList()));
            return res;
        }
    }
    

    题目描述

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

    思路

    有了之前的思想,解决办法就显而易见了,需要返回整个杨辉三角,可以从前往后开始递推。

    代码

    import java.util.ArrayList;
    
    public class Solution {
        public ArrayList<ArrayList<Integer>> generate(int numRows) {
            ArrayList<ArrayList<Integer>> res = new ArrayList();
            for (int i=0; i<numRows; i++){
                ArrayList<Integer> row = new ArrayList();
                for (int j=0; j<=i; j++){
                    if (j==0||j==i) row.add(1);
                    else {
                        Integer value = res.get(i-1).get(j-1) + res.get(i-1).get(j);
                        row.add(value);
                    }
                }
                res.add(row);
            }
            return res;
        }
    }
    

    相关文章

      网友评论

          本文标题:【leetcode】No.118&No.119:pascals-

          本文链接:https://www.haomeiwen.com/subject/jbwerctx.html