Recursive Arrangement
The main idea of Recursive Backtracking in Arrangement
P (n, m) is equivalent to placing a piece on each row of an M * n board, and ensure that each column has only one piece.
Each piece can be placed in N positions. Therefore, the position of each piece can be lifted from the first line, if a pawn is not removed from the column, it is placed from the starting position of the next row; otherwise, a column is put down. If there is no position available, it will be traced back (back to a row )... if M pieces are put down, the sequence of the columns where each piece is located is an arrangement that meets the requirements...
# Include <stdio. h>
# Include <string. h>
# Define N 5
# Define m 3
Int used [N], Count, B [m];
// Used records whether a certain number has been used, Count records the number of solutions, and B records the obtained solutions each time.
Void search (INT );
Int main ()
{
Memset (used, 0, N * sizeof (used [0]);
Search (0 );
Printf ("% d/N", count );
Return 0;
}
Void search (INT depth)
{
Int I;
If (depth = m) // find the solution that meets the conditions, the output
{
For (I = 0; I <m; I ++)
Printf ("% d", B [I]);
Printf ("/N ");
Count ++;
Return;
}
For (I = 0; I <n; I ++)
{
B [depth] = I + 1;
If (! Used [I]) // check whether it has been used
{
Used [I] = 1;
Search (depth + 1 );
Used [I] = 0;
}
}
}
Depth is the subscript of array B: Add 1 after the number is obtained, otherwise it will not change...
Implement combination with recursion:
Application of the "divide and conquer in recursion" in Arrangement
The combination of N numbers and M numbers is equivalent to using the formula C (n, m) = C (n-1, m) + C (n-1, m-1 ).
# Include <stdio. h>
# Define N 5
# Define m 3
Void search (INT, Int, INT );
Int B [m], count; // array B records the number of solutions produced each time, and count records the number of solutions.
Int main ()
{
Count = 0;
Search (0, n, m );
Printf ("% d/N", count );
Return 0;
}
Void search (INT depth, int N, int m)
{
Int I;
If (M = 0) // if the condition is met, the output is
{
For (I = 0; I <m; I ++)
Printf ("% d", B [I]);
Printf ("/N ");
Count ++;
Return;
}
If (M> N | n <= 0) return; // common sense pruning
B [depth] = N;
Search (depth + 1, n-1, m-1 );
B [depth] = 0;
Search (depth, n-1, M );
}