在Go(Golang)中编写帕斯卡尔三角形的程序

221 阅读1分钟

概述

我们的目标是找到帕斯卡三角形的打印行数n。数目n是作为程序的输入的。

例子1

Input: numRows = 4
Output: [[1],[1,1],[1,2,1],[1,3,3,1]]

例二

Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

请参考这个链接,了解更多关于帕斯卡三角形的信息 -en.wikipedia.org/wiki/Pascal…

我们的想法是在这里使用动态编程。

程序

下面是同样的程序

package main

import "fmt"

func generate(numRows int) [][]int {
	firstRow := []int{1}

	if numRows == 1 {
		return [][]int{firstRow}
	}

	secondRow := []int{1, 1}

	if numRows == 2 {
		return [][]int{firstRow, secondRow}
	}

	output := [][]int{firstRow, secondRow}

	for i := 2; i < numRows; i++ {
		temp := make([]int, i+1)

		lastRow := output[i-1]

		temp[0] = 1
		temp[i] = 1

		for j := 1; j < i; j++ {
			temp[j] = lastRow[j-1] + lastRow[j]
		}

		output = append(output, temp)

	}

	return output

}

func main() {
	output := generate(4)
	fmt.Println(output)

	output = generate(5)
	fmt.Println(output)
}

输出:

[1] [1 1] [1 2 1] [1 3 3 1]]
[[1] [1 1] [1 2 1] [1 3 3 1] [1 4 6 4 1]]