Pascal's Triangle, pascaltriangle
This article is in the study of the summary, welcome to reprint but please note the Source: http://blog.csdn.net/pistolove/article/details/41827325
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]]
Ideas:
(1) The Pascal's Triangle mentioned in this question is essentially the Yang Hui Triangle. The meaning of the question is given an integer N, and all the numbers included in line 1-N of the Yang Hui Triangle are output.
(2) Everyone must be familiar with the Yang Hui triangle. For each row in the triangle, the number of numbers in each row is equal to the number of rows, and the first and last numbers are 1, any number in the middle is the sum of the two numbers above the line.
(3) First, create a sequence list to store the numbers of each row. because the number of rows 1st and 2nd in the triangle are special, you need to judge and process them separately.
(4) Next, the system traverses N times in a loop, exactly corresponding to N rows. The number of rows equals 1 and returns the corresponding values respectively. If the number of rows is greater than 2, it needs to be traversed, if the first and last elements of the row are traversed, 1 is added to the row of the temporary linked list, it must be the addition of the corresponding elements in the previous row (if in m (m> 2), one element is k (1 <m-1 ), then the value of k is the K-1 element and the low k element in line 1), because the first two rows of numbers have been stored in rows in order, therefore, the order of the specified elements does not change.
(5) At last, each row is traversed and the temporary linked list is saved to rows. When the next row is traversed, the number of the previous row can be obtained based on the number of rows, to obtain the value of any number in the middle of the row.
(6) This question is still relatively simple. This article provides only one way to solve the problem. I have not considered time efficiency and space efficiency optimization. I hope it will help you. Thank you.
The algorithm code is implemented as follows:
Public static List <Integer> getAll (int num) {List <Integer> rows = new dynamic List <Integer> (); // If num is too large, it may cross-border for (int I = 1; I <= num; I ++) {List <Integer> row = new sort List <Integer> (); if (I = 1) {row. add (1);} if (I = 2) {row. add (1); row. add (1) ;}if (I >= 3) {for (int j = 0; j <I; j ++) {if (j = 0) {row. add (1);} else if (j = I-1) {row. add (1);} else if (j! = 0 & j! = I-1) {List <Integer> list = rows. get (I-2); row. add (list. get (j-1) + list. get (j) ;}} rows. add (row);} return rows ;}
When N = 10, the running result is as follows:
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84,126,126, 84, 36, 9, 1]