题目:输入一个正数n,输出所有和为n连续正数序列。
例如输入15,由于1+2+3+4+5=4+5+6=7+8=15,所以输出3个连续序列1-5、4-6和7-8。
例如输入15,由于1+2+3+4+5=4+5+6=7+8=15,所以输出3个连续序列1-5、4-6和7-8。
算法思路
采用辅助空间保存序列。用i从1开始做起点,j从i+1开始,直到i等于(1+n)/2
1、如果i-j的和等于n,则输出序列
2、如果i-j的和大于n,则将序列清空
3、如果i-j的和小于n,则将j假如到序列中
算法伪代码:
void CotinuousSeq(int n)
initialize a sequence
for i <- 1 to (1+n)/2
push first element
for j <- i+1 to (1+n)/2
if j+sum(tvec) <= n
then push into sequence
if sum(ivec) = n
then print the sequence and clear the sequence
else clear the sequence
C++实现
void CotinuousSeq(int n)
{
//initialize a sequence
vector<int> tvec;
//for i <- 1 to (1+n)/2
for(int i = 1; i <= (1+n)/2; ++i)
{
//push first element
tvec.push_back(i);
//for j <- i+1 to (1+n)/2
for(int j = i+1; j <= (1+n)/2; ++j)
{
//if j+sum(tvec) <= n
if((j + sum(tvec)) <= n)
{
//then push into sequence
tvec.push_back(j);
//if sum(ivec) = n
if(sum(tvec) == n)
{
//then print the sequence and clear the sequence
print(tvec);
tvec.clear();
break;
}
}
else
{
//else clear the sequence
tvec.clear();
break;
}
}
}
}