2022年4月9日 作者 zeroheart

dp第12天

搞两道简单题

118. 杨辉三角

/**
 118. 杨辉三角
 给定一个非负整数 numRows,生成「杨辉三角」的前 numRows 行。

 在「杨辉三角」中,每个数是它左上方和右上方的数的和。


 示例 1:

 输入: numRows = 5
 输出: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
 示例 2:

 输入: numRows = 1
 输出: [[1]]


 提示:

 1 <= numRows <= 30

 * @author zeroheart
 *
 */
public class Question118 {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> res = new ArrayList<>();
        int[][] dp = new int[numRows][numRows];
        for(int i = 0; i<numRows; i++){
            dp[i][0] = 1;
            dp[i][i] = 1;
        }
        List l0 = new ArrayList();
        l0.add(1);
        res.add(l0);
        for(int i=1; i<numRows; i++){
            List list = new ArrayList();
            list.add(1);
            for(int j=1; j<=i; j++){
                dp[i][j] = dp[i-1][j-1]+dp[i-1][j];
                list.add(dp[i][j]);
            }
            res.add(list);
        }
        return res;
    }

    public static void main(String[] args) {
    }
}

119. 杨辉三角 II

这题是输出某一行的值。。。上面的改一下就行。。。


/**
119. 杨辉三角 II
给定一个非负索引 rowIndex,返回「杨辉三角」的第 rowIndex 行。

在「杨辉三角」中,每个数是它左上方和右上方的数的和。


示例 1:

输入: rowIndex = 3
输出: [1,3,3,1]
示例 2:

输入: rowIndex = 0
输出: [1]
示例 3:

输入: rowIndex = 1
输出: [1,1]


提示:

0 <= rowIndex <= 33


进阶:

你可以优化你的算法到 O(rowIndex) 空间复杂度吗?

* @author zeroheart
*
*/
public class Question119 {
public List<Integer> getRow(int rowIndex) {
int numRows = rowIndex + 1;
List<List<Integer>> res = new ArrayList<>();
int[][] dp = new int[numRows][numRows];
for(int i = 0; i<numRows; i++){
dp[i][0] = 1;
dp[i][i] = 1;
}
List l0 = new ArrayList();
l0.add(1);
res.add(l0);
for(int i=1; i<numRows; i++){
List list = new ArrayList();
list.add(1);
for(int j=1; j<=i; j++){
dp[i][j] = dp[i-1][j-1]+dp[i-1][j];
list.add(dp[i][j]);
}
res.add(list);
}

return res.get(rowIndex);
}

public static void main(String[] args) {
}
}