Question: enter an integer s to print all consecutive integer sequences (containing at least two numbers) for s ). For example, if input 9 is used, two sequences (2, 3, 4, 4, and 5) are output.
Solution 1: because a sequence requires at least two numbers, the upper limit of the two numbers is (1 + s)/2. We can enumerate the starting and ending points of the sequence to find all the satisfied sequences. The time complexity is O (n ^ 2), which is relatively low.
Solution 2: we set two pointers, start and end, to indicate the start and end of the Current sequence respectively, and remember the sum of the sequence and sum. When sum = s, this sequence is output, and end moves one bit backward. If sum> s, start moves one bit backward. If sum <s, then the end will move one digit backwards.
Until start <(1 + s)/2 ends the cycle, time complexity O (n), High Efficiency
# Include
# Include
# Include
# Define deusing namespace std; // print the sequence void PrintNum (int start, int end) {for (int I = start; I <= end; I ++) {printf ("% d", I) ;}printf ("\ n") ;}// locate the sum of the two numbers and svoid FindSequenceSum (int s) {if (s <3) {// return;} int start = 1; int end = 2; int sum = 3; int mid = (1 + s)> 1; // cyclically locate all the while (start <mid) {// the starting point of the sequence must be less than half of (1 + s) if (sum = s) {// print PrintNum (start, end); end ++; sum + = end;} else if (sum> s) directly for the sum sequence) {// and the sequence greater than s move a sum-= start; start ++;} from the start point ;} else {// and the sequence smaller than s move one end ++; sum + = end ;}} int main () {FindSequenceSum (9 ); getchar (); return 0 ;}