题目描述
- 输入一个正数s,打印出所有和为s的连续正数序列(至少含有两个数)。例如输入15,由于1+2+3+4+5=4+5+6=7+8=15,所以结果打印出3个连续序列1~5、4~6和7~8。
算法分析
- 初始化small=1,big=2;
- small到big序列和小于sum,big++;
- 大于sum,small++;
- 当small增加到(1+sum)/2是停止
提交代码:
class Solution {
public:
vector<vector<int> > FindContinuousSequence(int sum) {
if (sum < 1)
return vector<vector<int> >();
int start = 1, end = 2;
int curSum = start + end;
int lastIndex = (sum + 1) / 2;
vector<vector<int> > result;
while (start < lastIndex)
{
if (curSum == sum)
{
vector<int> temp;
for (int i = start; i <= end; ++i)
temp.push_back(i);
result.push_back(temp);
++end;
curSum += end;
}
else if (curSum > sum)
{
curSum -= start;
++start;
}
else
{
++end;
curSum += end;
}
}
return result;
}
};
测试代码:
// ====================测试代码====================
void Test(const char* testName, int sum)
{
if (testName != nullptr)
printf("%s for %d begins: \n", testName, sum);
Solution s;
vector<vector<int> > result = s.FindContinuousSequence(sum);
for (vector<int> &vec : result)
{
for (int &each : vec)
cout << each << " ";
cout << endl;
}
}
int main(int argc, char* argv[])
{
Test("test1", 1);
Test("test2", 3);
Test("test3", 4);
Test("test4", 9);
Test("test5", 15);
Test("test6", 100);
return 0;
}