题目

输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。
序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。

示例 1:
输入:target = 9
输出:[[2,3,4],[4,5]]

示例 2:
输入:target = 15
输出:[[1,2,3,4,5],[4,5,6],[7,8]]

限制:
1 <= target <= 10^5

方案一(穷举)

  1. func findContinuousSequence(target int) [][]int {
  2. if target < 3 {
  3. return [][]int{}
  4. }
  5. ret := [][]int{}
  6. for i := 1; i <= target / 2; i++ {
  7. count := 0
  8. nums := []int{}
  9. for j := i; true; j++ {
  10. count += j
  11. nums = append(nums, j)
  12. if count >= target {
  13. if count == target {
  14. ret = append(ret, nums)
  15. }
  16. break
  17. }
  18. }
  19. }
  20. return ret
  21. }

方案二(滑动窗口)

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/