题目
输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。
序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。
示例 1:
输入:target = 9
输出:[[2,3,4],[4,5]]
示例 2:
输入:target = 15
输出:[[1,2,3,4,5],[4,5,6],[7,8]]
方案一(穷举)
func findContinuousSequence(target int) [][]int {
if target < 3 {
return [][]int{}
}
ret := [][]int{}
for i := 1; i <= target / 2; i++ {
count := 0
nums := []int{}
for j := i; true; j++ {
count += j
nums = append(nums, j)
if count >= target {
if count == target {
ret = append(ret, nums)
}
break
}
}
}
return ret
}
方案二(滑动窗口)
func findContinuousSequence(target int) [][]int {
if target < 3 {
return [][]int{}
}
list := []int{}
// 注意这里的 +2
for i := 1; i <= target / 2 + 2; i++ {
list = append(list, i)
}
ret := [][]int{}
// 双指针
i, j, count := 0, 0, 0
for j < len(list) {
if count < target {
count += list[j]
j += 1
} else if count > target {
count -= list[i]
i += 1
} else {
ret = append(ret, list[i:j])
count -= list[i]
i += 1
}
}
return ret
}
原文
https://leetcode-cn.com/leetbook/read/illustrate-lcof/504usr/
https://leetcode-cn.com/leetbook/read/illustrate-lcof/5017gs/