// 面试题57(二):为s的连续正数序列 // 题目:输入一个正数s,打印出所有和为s的连续正数序列(至少含有两个数)。 // 例如输入15,由于1+2+3+4+5=4+5+6=7+8=15,所以结果打印出3个连续序列1~5、 // 4~6和7~8。 #include <cstdio> void PrintContinuousSequence(int small, int big); void FindContinuousSequence(int sum) { if (sum < 3) return; int small = 1; int big = 2; int middel = (1 + sum) / 2; //s的中位数, 因为至少包含2个数字 int curSum = small + big; while (small < middel) { if (curSum == sum) PrintContinuousSequence(small, big); while (curSum > sum && small < middel) //若结果大于s, 则应减少最小数字 { curSum -= small; ++small; if (curSum == sum) PrintContinuousSequence(small, big); } ++big; curSum += big; //若结果小于s, 则应包含更多数字 } } void PrintContinuousSequence(int small, int big) { for (int i = small; i <= big; ++i) printf("%d ", i); printf(" "); }
// ====================测试代码==================== void Test(const char* testName, int sum) { if (testName != nullptr) printf("%s for %d begins: ", testName, sum); FindContinuousSequence(sum); } 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; }
分析:妙啊。
class Solution { public: vector<vector<int> > FindContinuousSequence(int sum) { int small = 1; int big = 2; int middle = (sum + 1) >> 1; int curSum = small + big; vector<vector<int> > result; while (small < middle) { if (curSum == sum) vectorPush(result, small, big); while (curSum > sum && small < middle) { curSum -= small; ++small; if (curSum == sum) vectorPush(result, small, big); } ++big; curSum += big; } return result; } vector<vector<int> > vectorPush(vector<vector<int> > &result, int small, int big) //注意引用 { vector<int> temp; for (int i = small; i <= big; ++i) temp.push_back(i); result.push_back(temp); return result; } };