Continue to create, accelerate growth! This is the second day of my participation in the "Nuggets Daily New Plan · October Update Challenge", click to view the event details
Dynamic programming is a mathematical idea of solving decision-making problems in stages. It solves complex problems by decomposing the original problem into simple sub-problems.
Yang Hui Triangle
Given a non-negative integer numRows
, generate the front numRows
row .
In the Yanghui Triangle, each number is the sum of its upper left and upper right numbers.
Example 1:
输入: numRows = 5
输出: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
复制代码
Example 2:
输入: numRows = 1
输出: [[1]]
复制代码
Yang Hui's triangle is a geometric arrangement of binomial coefficients in a triangle, which appeared in the book "Detailed Explanation of the Nine-Chapter Algorithm" written by Yang Hui, a mathematician in the Southern Song Dynasty, in 1261.
It has the following properties:
- The numbers in each row are symmetrical, starting from 1 and gradually becoming larger and then smaller, and finally back to 1. The first and last numbers in each row are both 1, that is,
dp[i][0] = 1
anddp[i][i] = 1
- Each number is equal to the sum of the left and right numbers in the previous row. which is
dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]
Solution 1
fun generate(numRows: Int): List<List<Int>> {
val dp = Array(numRows) { IntArray(numRows) }
for (index in 0 until numRows) {
dp[index][0] = 1
dp[index][index] = 1
}
for (i in 2 until numRows) {
for (j in 1 until i) {
dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]
}
}
val result = ArrayList<ArrayList<Int>>()
dp.forEach {
val r = ArrayList<Int>()
it.forEach {
if (it != 0) {
r.add(it)
}
}
result.add(r)
}
return result
}
复制代码
Solution 2
- According to the example, it can be seen that each of its arrays has different lengths, and the length can be determined according to the nth line.
- For each line of numbers, the first and second lines are 1s, and the other lines start and end with 1s. It is directly judged that when j == 0 || j == n-1, the assignment is 1.
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
List<Integer> item = new ArrayList<>();
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
item.add(1);
continue;
}
List<Integer> pre = result.get(i - 1);
item.add(pre.get(j - 1) + pre.get(j));
}
result.add(item);
}
return result;
}
复制代码
the complexity
- Time complexity: O(n^2), you need to traverse to generate each value.
- Space complexity: O(n^2), every number needs to be stored.