package practices
var NUMS = []int{
1, 5, 2, 3, 6, 9, 10, 4, 5, 55, 13, 12, 16, 17, 18, 20,
18, 59, 2, 3, 6, 9, 10, 4, 5, 855, 13, 12, 16, 417, 18, 20,
19, 500, 2, 3, 6, 9, 10, 4, 5, 755, 13, 212, 516, 517, 118, 120,
100, 501, 42, 3, 6, 9, 610, 4, 611, 655, 616, 312, 116, 617, 118,
18, 59, 2, 53, 6, 9, 10, 74, 5, 55, 513, 12, 416, 117, 178, 120,
19, 500, 2, 63, 618, 9, 619, 84, 5, 620, 413, 12, 516, 217, 718, 120,
100, 501, 2, 73, 6, 89, 10, 94, 5, 55, 133, 12, 616, 170, 718, 800,
}
func FindLongestSequence(nums []int, index int) int {
// 定义出口
if nums == nil {
return 0
}
if index <= 0 {
return 1
}
length := len(nums)
if length == 0 || length == 1 {
return length
}
// 比较当前第index的值和index-1的值的大小
numBefore := nums[index-1]
numThis := nums[index]
if numBefore < numThis {
// 如果当前值大,则最长子序列长度就是 前index-1个长度的子序列计算出的最大长度+1
return 1 + FindLongestSequence(nums, index-1)
} else {
// 否则最大长度和index-1序列的最大长度相同
return FindLongestSequence(nums, index-1)
}
}
func main() {
t1 := time.Now().UnixNano() / 1e6
sum := practices.FindLongestSequence(practices.NUMS, len(practices.NUMS)-1)
t2 := time.Now().UnixNano() / 1e6
fmt.Println("===", sum, "\nt1=", t1, "\nt2=", t2, "\ntimeCost:=", t2-t1)
}
执行结果如下:
这个问题很简单,源代码注释写的有每一步骤的思路。每一个子序列的最大长度只用计算一次。