Here is an example,
In N numbers, you can find K numbers (k <= N) to print all possible conditions. For example, 0, 1, 2 Find 2 numbers in the three numbers, Print 0, 1 0, 2 1, 2 This classic problem can be solved by Recursive Backtracking or iterative backtracking. Recursive tracing is easier to understand.
1 # Include < Iostream >
2 # Include < Vector >
3 Using Namespace STD;
4 // N = 3 k = 2 0 1 2
5 // Output 0 1
6 // 0 2
7 // 1 2
8 // Int for_loop (vector <int> & S, int N, int K, int L = 1 ){
9 //
10
11 Void Ouput (vector < Int > & S, Int K ){
12 For ( Int J = 1 ; J <= K; j ++ )
13 Cout < S [J] < " " ;
14 Cout < Endl;
15 }
16
17
18 // S [0] is Shao Bing, start from S [1]
19 // Recursive Backtracking
20 Void For_loop (vector < Int > & S, Int N, Int K, Int L ){
21 For (S [l] = S [L - 1 ] + 1 ; S [l] < N; s [l] ++ ){
22 If (L = K ){
23 Ouput (S, k );
24 } Else {
25 // For_loop (S, N, K, L ++ ); // Well l ++ not acceptable !!! L ++ means l will not change !!
26 For_loop (S, N, K, L + 1 );
27 }
28 }
29
30 }
31
32 // Same as aboveAlgorithmHowever, recursion is eliminated.
33 // Recursive Backtracking, like the eight queens problem, essentially and
34 // Multiple for loops are the same,
35 // For (INT I = 0; I = 10; I ++)
36 // For (Int J = 0; j <10; j ++) // I = 0 into the stack, j = 09 finished I = 0 back stack, I + 1 continue
37 // The key is to use recursion and deep-first search. When n-layer search is complete, it is returned to n-1.
38 // Instead of recursion, We need to simulate the return process in the loop. We need to be able to return to the correct location, similar to the nature of the inbound and outbound stack.
39 // In some cases, we do not need to explicitly mark the existence of the stack.
40 // For (INT I = 0 ;..)
41 // For (Int J = I + 1 ;..) // Instead of for (Int J = 1 ;)
42 // At first l = 1
43 Void For_loop_norec (vector < Int > & S, Int N, Int K, Int L ){
44 S [l] = 0 ; // S [1] = 0;
45 While (L ){
46 While (S [l] < N ){ // Process current Layer
47 If (L = K ){ // Reach the lowest layer and print the result
48 Ouput (S, k );
49 S [l] + = 1 ; //
50 } Else { // Otherwise, the depth takes precedence and enters the next layer.
51 L + = 1 ;
52 S [l] = S [L - 1 ] + 1 ;
53 }
54 }
55 L -- ; // The following process is complete and jumps back to the previous layer.
56 S [l] + = 1 ; // To the next POS on this level
57 }
58 }
59
60
61
62
63 Int Main ( Int Argc, Char * Argv []) {
64
65 Int N = 6 ;
66 Int K = 3 ;
67 Vector < Int > S (n + 1 , - 1 );
68
69 For_loop (S, N, K, 1 );
70
71 Cout < " No rec version " < Endl;
72
73 For_loop_norec (S, N, K, 1 );
74
75 Return 1 ;
76 }