Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Example 1:
Input: rowIndex = 3
Output: [1,3,3,1]
Example 2:
Input: rowIndex = 0
Output: [1]
Example 3:
Input: rowIndex = 1
Output: [1,1]
Constraints:
Follow up: Could you optimize your algorithm to use only O(rowIndex) extra space?
func getRow(rowIndex int) []int {
rowIndex++
pa := make([][]int, rowIndex)
for i := 0; i < rowIndex; i++ {
pa[i] = make([]int, i+1)
pa[i][0], pa[i][i] = 1, 1
for j := 1; j < len(pa[i])-1; j++ {
if i > 1 {
pa[i][j] = pa[i-1][j] + pa[i-1][j-1]
}
}
}
re := make([]int, rowIndex)
copy(re, pa[rowIndex-1])
return re
}
https://go.dev/play/p/LK-SEl3SxM2
func getRow(rowIndex int) []int {
prev := make([]int, 1)
prev[0] = 1
if rowIndex == 0 {
return prev
}
row := 0
for {
row++
arr := make([]int, row + 1)
arr[0] = 1
arr[row] = 1
for ind := 1; ind < row; ind++ {
arr[ind] = prev[ind - 1] + prev[ind]
}
prev = arr
if rowIndex == row {
break
}
}
return prev
}
func getRow(n int) []int {
row := []int{1}
for k := 1; k <= n; k++ {
row = append(row, row[len(row)-1] * (n - k + 1)/k)
}
return row
}
func getRow(rowIndex int) []int {
arr := make([] int, rowIndex+1)
arr[0] = 1
for i := 0 ; i <= rowIndex ; i++ {
for j := i ; j > 0 ; j-- {
arr[j] += arr[j-1]
}
}
return arr
}
func getRow(rowIndex int) []int {
rs := make([]int, rowIndex + 1)
if rowIndex >= 0 {
rs[0] = 1
}
if rowIndex >= 1 {
rs[0] = 1
rs[1] = 1
}
if rowIndex <= 1 {
return rs
}
for i := 2; i <= rowIndex; i++ {
rs[i] = 1
for j := 1; j <= i / 2; j++ {
rs[i - j] = rs[j - 1] + rs[j]
}
for j := 1; j <= i / 2; j++ {
rs[j] = rs[i - j]
}
}
return rs
}
func getRow(rowIndex int) []int {
res := make([][]int, rowIndex+1)
res[0] = []int{1}
for i := 1; i <= rowIndex; i++ {
res[i] = make([]int, i+1)
res[i][0] = 1
res[i][i] = 1
for j := 1; j < i; j++ {
res[i][j] = res[i-1][j-1] + res[i-1][j]
}
}
return res[rowIndex]
}
func getRow(rowIndex int) []int {
result := [][]int{[]int{1}, []int{1, 1}}
row := []int{}
if rowIndex == 0 {
return result[0]
}
if rowIndex == 1 {
return result[1]
}
for i := 2; i <= rowIndex; i++ {
prevArray := result[i-1]
leftIdx := 0
rightIdx := 1
current := []int{1}
for leftIdx < rightIdx && rightIdx < len(prevArray) {
left := prevArray[leftIdx]
right := prevArray[rightIdx]
current = append(current, left+right)
leftIdx += 1
rightIdx += 1
}
current = append(current, 1)
row = current
result = append(result, current)
}
return row
}
[Go] Array and string - Reverse Words in a String III (0) | 2022.04.16 |
---|---|
[Go] Array and string - Reverse Words in a String (0) | 2022.04.16 |
[Go] Array and string - Rotate Array (0) | 2022.04.14 |
[Go] Array and String - Minimum Size Subarray Sum (0) | 2022.04.13 |
[Go] Two-pointer Technique - Scenario II (0) | 2022.04.12 |
댓글 영역