Given an integer numRows, return the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Example 1:
Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
Example 2:
Input: numRows = 1
Output: [[1]]
Constraints:
func generate(numRows int) [][]int {
temp := make([][]int, numRows)
for i := 0; i < numRows; i++ {
temp[i] = make([]int, i+1)
temp[i][0], temp[i][i] = 1, 1
if i > 1 {
for j := 1; j < len(temp[i])-1; j++ {
temp[i][j] = temp[i-1][j] + temp[i-1][j-1]
}
}
}
return temp
}
https://go.dev/play/p/iG5EHfUEGM5
func generate(numRows int) [][]int {
var res [][]int
for i := 0;i < numRows;i++{
var tmp []int = make([]int,i+1)
tmp[0] = 1
res = append(res, tmp)
for j := 1;j <= i;j++{
if i == j{
res[i][j] = 1
} else{
res[i][j] = res[i-1][j-1] + res[i-1][j]
}
}
}
return res
}
func generate(numRows int) [][]int {
if numRows == 0 {
return nil
}
triangle := make([][]int, numRows)
for i := 0; i < numRows; i++ {
triangle[i] = make([]int, i+1)
row := triangle[i]
n := len(row)
row[0] = 1
row[n-1] = 1
if i <= 1 {
continue
}
prevRow := triangle[i-1]
for j := 1; j < n-1; j++ {
row[j] = prevRow[j-1] + prevRow[j]
}
}
return triangle
}
func generate(numRows int) [][]int {
row := []int{1}
rows := [][]int{row}
if numRows == 1 {
return rows
}
for i:=1;i<numRows;i++ {
rows = append(rows, generateFromAboveRow(rows[i-1]))
}
return rows
}
func generateFromAboveRow(row []int) []int {
i := 0
res := []int{1}
for i+1<len(row) {
res = append(res, row[i]+row[i+1])
i++
}
res = append(res, 1)
return res
}
func generate(numRows int) [][]int {
var result [][]int = make([][]int, numRows)
result[0] = []int{1}
for i := 1; i < numRows; i++ {
var row []int = make([]int, i+1)
row[0] = 1
row[i] = 1
for j := 1; j < i; j++ {
row[j] = result[i-1][j-1] + result[i-1][j]
}
result[i] = row
}
return result
}
[Go] Array and string - Immutable String - Problems & Solutions (0) | 2022.04.02 |
---|---|
Array and string - Introduction to String from Java to Go (0) | 2022.03.30 |
[Go] Array and String - Spiral Matrix (0) | 2022.03.29 |
[Go] Array and string - Diagonal Traverse (1) | 2022.03.27 |
Array and string - Introduction to 2D Array from Java to Go (1) | 2022.03.27 |
댓글 영역