【剑指offer】和为S的连续正整数序列

来源:互联网 发布:3米直尺道路检测数据 编辑:程序博客网 时间:2024/05/29 07:42

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

分析:做这一题我们定义整数left和right分别为1和2,left到right累加的和为t,当t<sum时,right++,t也加上right,当t>sum时,t减去left后left++,当t=sum时就把left到right的数保存起来。只要left小于right,就不断重复上面的过程,只有在left+1=right并且t>sum时才跳出循环。

程序:

vector<vector<int> > FindContinuousSequence(int sum) {vector<vector<int>>  res;if(sum<3)  return res;int left=1,right=2,t=3;while(left<right) {while(t<sum)  {right++;t+=right;}while(t>sum&&left<right)  {t-=left;left++;}if(left==right) {right++;t+=right;}if(t==sum)  {vector<int>  temp;int l=left;while(l<=right) temp.push_back(l++); res.push_back(temp);right++;t=t+right;}if(left+1==right&&left+right>sum) break;}return res;}