A description of the topic
There is an array a[1000] with 1000 integers in it, find all the pairs of numbers and m in the array. For example, the array is-1,2,4,6,5,3,4,2,9,0,8,3, then and the number of 8 pairs has ( -1,9), (2,6), (4,4), (5,3), (5,3), (0,8).
Second, the most common algorithm
In the case of irreducible complexity, the simplest algorithm for this problem is as follows:
private static List<int[]> UseNormalWay(int[] arr, int sumTotal)
{
List<int[]> result = new List<int[]>();
for (int i = 0; i < arr.Length; i++)
{
int expectNum = sumTotal - arr[i];
for (int j = i + 1; j < arr.Length; j++)
{
if (arr[j] == expectNum)
{
result.Add(new int[]{arr[i], expectNum});
}
}
}
return result;
}
Use a two-tier loop to find all the pairs of numbers that are sumtotal for a fixed number, and the number pairs to be found in the list. But the complexity of the algorithm is a bit high, actually doing some repetitive work while traversing:
1 There is no need to deal with the previously paired sequence in the subsequent cycle.
2 when looking for numbers that are sumtotal with a certain number, there should be some processes that can be used with each other.
Based on these two points, it is possible to refer to the idea of 01 backpacks or dynamic programming (perhaps improperly cited, and I have a superficial understanding of both ideas and understandings) to improve the algorithm and use the recursive operation.