Classification of algorithm problems-Summary of integers and problem Series

Source: Internet
Author: User

1. Given a positive integer N, list all continuous positive integer strings whose sum is N.

Method 1:

Two numbers small and big can be used to represent the minimum and maximum values of the sequence respectively. First, initialize small to 1 and big to 2. If the sum of the sequences from small to Big is greater than N, the right-shift small removes the smallest number from the sequence. If the sum of the sequences from small to Big is less than N, then shift big to the right, which is equivalent to adding the next number to the sequence until small is equal to (1 + N)/2, so that there are at least two numbers in the sequence.

Method 2:

Set the maximum length to X (the maximum number of elements that add up to the same value, then these elements are taken from the smallest element), then

1 + 2 +... + x = n => X (X + 1)/2 = N

=> X = SQRT (2n + 1/4)-1/2 <= SQRT (2n)

If the length of the Child sequence to be obtained is Len, you can find the child sequence from Len = x --> 1.

If the element value at the starting position of the sequence is S, the sub-order with the length of Len is

S, S + 1,... S + X-1

The subsequence is x * s + x (x-1)/2 = n => S = N/X-(x-1)/2

If s is an integer, then S, S + 1,... S + X-1 is the Child sequence that meets the condition.

Code (from the Internet ):

# Include <stdio. h> # include <math. h> int main () {int m = 0, n = 0, start = 0, end = 0, flag = 0; // M indicates the number of inputs, N indicates the number of positive integer sequences, start indicates the Start positive integer, end indicates the ending positive integer, // flag indicates whether a sequence that meets the conditions exists, 0 (default) does not, 1 has float temp = 0.0; printf ("Please input a integer:"); scanf ("% d", & M); printf ("\ n "); N = (INT) (SQRT (double) M) * SQRT (double) 2); // obtain the maximum number of sequences possible while (n> = 2) {temp = (float) M/N-(float) (n-1)/2; // evaluate the start number if (temp = (INT) temp) {// determine whether it is a positive integer, that is, whether a sequence that meets the conditions exists for (flag = 1, start = (INT) temp, end = start + N; Start <end; start ++) {// set the flag to 1. If a sequence that meets the conditions exists, the start integer and end integer end printf ("% d", start) are obtained ); printf ("");} printf ("\ n");} n --;} If (flag = 0) // no matching sequence exists, output "NONE" printf ("NONE ");}

2. sum of two numbers of S

Enter an incremental sorting array and a number S, and search for two numbers in the array. Yes, their sum is exactly S. If there are multiple pairs of numbers and the sum is equal to S, the product of the two numbers is the smallest.

Thought: because the order has been sorted, if there are two numbers, it may be a relatively large one, a relatively small one, or a relatively equal two! So let's set a n1 = min (that is, a [0]), n2 = max (that is, a [n-1]), which is actually n1 = A [low], low = 0 start, n2 = A [High], high = n-1 start, then N1 + N2 compare with S (We Need To sum), if>, n2 = A [-- high]; If <, n1 = A [++ low], and if =, use Mul to save the product, and save two numbers, because there may be more than one pair of numbers, as long as the product is small! Scan until low> = high ends!


3. Determine whether I, j, and K exist in a [I] + A [J] = A [k] containing N integers. The minimum time complexity is:

A.o (N ^ 2) B. O (N ^ 2 * logn) C. O (N ^ 3) D. O (nlogn)

Analysis: First incremental sorting (O (nlgn), then fixed each element, according to the two numeric s that sum into S (n * O (N) = O (N ^ 2 ))

Sum (leetcode 2sum, 3sum, 4Sum, K sum)


I once saw a post on the Internet to discuss the O (nlgn) method. Unfortunately, I still cannot find it, probably using the idea of the opposite number.


4. enter two integers, N and m, from the series 1, 2, 3 ....... N is random, so that the sum is equal to M. All the possible combinations must be listed. (0-1 backpack problem)


The problem is actually a 0/1 backpack problem. For each n, we adopt a greedy strategy to first check whether N is obtained. If n is obtained, the subproblem becomes find (n-1, m-N). If n is discarded, The subproblem is find (n-1, m ).

So, how to develop a judgment policy for the solution? We know that recursion requiresBoundary ConditionFor the knapsack problem, there are only two boundary conditions. If n <1 or M <1, it is equivalent to "overflow" and cannot combo out M, another possibility is that M = N is satisfied in the remaining N, that is, the backpack is filled up and a group of solution units are output. In addition, nothing else. To reduce the recursive depth, when n> M, because the number equal to and equal to m must be less than or equal to M, you can set n = m.


1. First, it is judged that if n> m, the number of N greater than m cannot be involved in the combination, and n = m is set at this time;

2. If n is added to the maximum number N and n = m, the condition is met and the result is output;

3. Solve N in two cases: N is not added, n = n-1, M = m, recursion;

4. Add n, n = n-1, M = m-N, and recursion.

5. End.

Code (from the Internet ):

Intlength;/* enter two integers n and m, from the series ,,....... N is random, so that the sum is equal to M. All possibilities are required .. */voidfindcombination (int n, intm, bool * flag) {If (n <1 | M <1) return; If (n> m) // -- Reduce the number of recursion ---- n = m; If (n = m) {flag [n-1] = 1; for (INTI = 0; I <length; I ++) {If (flag [I] = true) printf ("% d \ t", I + 1);} printf ("\ n "); flag [n-1] = 0;} flag [n-1] = 1; findcombination (n-1, M-N, flag); flag [n-1] = 0; findcombination (n-1, m, flag) ;}intmain () {int n, m; printf ("n sum \ n"); scanf ("% d", & N, & M ); length = N; bool * flag = (bool *) malloc (sizeof (bool) * length); findcombination (n, m, flag); free (FLAG); Return 0 ;}

5. subset and problem (backtracking state space tree) --- promotion of Issue 4

Evaluate a given set consisting of n positive integers S = {S1, S2 ,... Subset of sn}. The sum of the subset is equal to a given positive integer d. For example, for S = {1, 2, 6, 8} and D = 9, the problem has two solutions: {1, 2, 6} and {1, 8 }. Of course, some instances of this problem are unsolvable.

Train of Thought: sort the set elements in ascending order, that is, S1 <= S2 <=... <= Sn

We can construct a state space tree in the form of a binary tree. The root of the tree represents the starting point, and no decision has been made on the given elements. The left and right sub-nodes of the root contain or do not contain S1 in the child set currently requested. Similarly, if you want to leave the first node to the left, the table name contains S2, and the right to the left is not included, and so on. Therefore, the path from the root to a layer-I node in the tree indicates which numbers are included in the subset represented by the node.

We record the numbers and S' in the node. IfS 'is equal to dThen we can find a solution to the problem.IfS 'is not equal to D. when either of the following two equations is trueTo terminate the node.

Code (original ):

# Include <iostream> # include <algorithm> using namespace STD; int arr [] = {8, 4, 5, 6, 9, 2, 1 }; /// int arr [] = {9, 8, 7, 6, 5, 4, 3, 2, 1}; // int arr [] = {1, 2, 4, 5, 6, 7, 8, 9, 10 }; const int Len = sizeof (ARR)/sizeof (INT); bool * flag = new bool [Len]; bool CMP (int x, int y); void getsubsetsum (int n, int S); int sum (int n); int main () {int S = 10; sort (ARR, arr + Len, CMP ); // sort by descfor (INT I = 0; I <Len; I ++) Flag [I] = false; getsubsetsum (len-1, S); Return 0 ;} void getsubsetsum (int n, int s) {If (S = 0) // solution {for (INT I = 0; I <Len; I ++) {If (flag [I] = true) {cout <arr [I] <""; // flag [I] = false ;}} cout <Endl;} If (S <arr [N] | S> sum (N) // return is too small or returns are mostly unsolved; // state space tree branch // contains arr [N] flag [N] = true; getsubsetsum (n-1, S-Arr [N]); // arr [N] flag [N] = false; getsubsetsum (n-1, S);} int sum (int n) {int S = 0; // For (INT I = 0; I <n; I ++) for (INT I = 0; I <= N; I ++) S + = arr [I]; return s;} bool CMP (INT X, int y) {return Y <X ;}

6. The largest sum of sub-Arrays

When we add a positive number, it will increase; when we add a negative number, it will decrease.

If the current sum is a negative number, the sum should be discarded and cleared again in the following tired addition; otherwise, the negative number will be reduced;

If the current sum is greater than the largest sum, the greatest sum is reset;

The input must be processed in special cases. When All integers in the input array are negative, the maximum value of the sub-array and the sub-array is the maximum element in the array.

Record resetting the current and current array subscript and the last reset of the largest and array subscript, You can output each element of the Child array.


// The largest subarray and [algorithm] void maxsum (INT array [], unsigned int Len) {int beg = 0, last = 0; // start the sum and the position where the maximum value is last updated if (null = array | Len <= 0) {return;} int cursum = 0, maxsum = 0; int I = 0; for (I = 0; I <Len; I ++) {cursum + = array [I]; // accumulate if (cursum <0) {//-key2 -- current and less than 0, reset to 0beg = I + 1; // cursum = 0;} If (cursum> maxsum) {//-key1 -- current and greater than the largest sum, the maximum sum is reset -- (3, 10,-4, 7, 2,-5, 4, 2) maxsum = cursum; last = I; //}/* The input must be processed in special cases. When All integers in the input array are negative, the maximum value of the sub-array and the sub-array is the maximum element in the array. */If (maxsum = 0) {//-key3 -- the maximum sum is still 0, indicating that all elements in the array are negative values maxsum = array [0]; for (I = 1; I <Len; I ++) {If (array [I]> maxsum) {maxsum = array [I]; BEG = I; last = I ;}}cout <"maxsum:" <maxsum <Endl; cout <"sub arr is:" <Endl; for (I = beg; I <= last; I ++) cout <array [I] <""; cout <Endl ;}

7. Put N eggs in M baskets

There are n eggs and M baskets. Put the eggs in M baskets. Each basket cannot be empty. In addition, it must be satisfied that any positive integer less than N can be obtained by the sum of the number of eggs in a certain basket. Write the program so that the input (n, m) Outputs all possible allocations.

Classification of algorithm problems-Summary of integers and problem Series

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.