题目描述
小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck! 输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序
解法
定义两个指针low,high,一开始分别为1和2,然后求high到low之间序列的和,然后和目标数字sum进行比较,若大于,则low++,小于则high++;上限为(sum/2)+1;
代码
vector<vector<int> > FindContinuousSequence(int sum) {
vector<vector<int>> retdata;
if (sum <= 2) return retdata;
int max = (sum / 2) + 1;
int low = 1;
int high = low+1;
while (low < high) {
if (BeforNSum(low, high) == sum) {
vector<int> temp;
for (int i = low; i <= high; i++) {
temp.push_back(i);
}
retdata.push_back(temp);
low++;
if (high != max) high++;
continue;
}
if (BeforNSum(low, high) > sum) {
low++;
continue;
}
if (BeforNSum(low, high) < sum) {
if (high != max) high++;
continue;
}
}
return retdata;
}
int BeforNSum(int low, int high) {
return ((high * (high + 1)) / 2) - (((low - 1) * ((low - 1) + 1)) / 2);
}