剑指offer——和为s的连续正数序列

用两个指针,如果和>sum,l++,如果和

class Solution {
public:
	vector> FindContinuousSequence(int sum) {
		vector> result;
		if (sum < 3)
			return result;

		int s = 3;  //s=[l.....r]区间内的和
		int l = 1, r = 2;
		while (l < sum&&r  res;
				for (int i = l; i <= r; i++)
					res.push_back(i);
				result.push_back(res);
				r++;
				s = s + r;
			}
			else if (s < sum)
			{
				r++;
				s = s + r;
			}
			else
			{
				s = s - l;
				l++;
			}
		}
		return result;
	}
};

你可能感兴趣的:(c++)