Find Continuous Sequence Sum to Target

DP, BruteForce

2. 题目描述

小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!

返回值描述:

示例1

输入

复制

返回值

复制

3. 思路

  1. sliding window:

    1. use a sliding window and move fast point forward when sum of window < target

    2. move slow pointer forward when sum of window > target

    3. append element between slow and fast pointers when sum of window == target

    4. stop when fast >= len(arr)

    5. Time: O(n*k), k = step move the slow pointer, in worse case k = window size. n= size of array

4. Coding

穷举法

Sliding window method

Last updated

Was this helpful?