Week 2: recursion (this week is super fast ~ ~)

Recursion: a function calls itself
Recursion = law + termination condition

Example 1: factorial

Description:
n! Recursive function of

Code:

int Factorial(int n)
{
    if(n == 1)
      return 1;
    else
      reurn n * Factorial(n-1);
}

Example 2: Hanoi Tower problem

Description:
In ancient times, there was a Vatican tower. There were three seats a, B, C and A. There were 64 plates on the tower. The plates were of different sizes. The big ones were at the bottom and the small ones were at the top. One monk wants to move the 64 plates from seat a to seat C, but only one plate can be moved at a time. In the process of moving, the plates on the three seats always keep the big plate at the bottom and the small plate at the top. In the process of moving, seat B can be used to output the steps of moving.

Code:

#include <iostream>
using namespace std;
void Hanoi(int n, char src, char mid, char dest)
//Move n plates on src seat to dest seat with mid seat as transfer
{
    if(n == 1) {//Just move one plate
        cout << src << "->" << dest << endl;
    //Move the plate directly from src to dest
        return ;//Recursive termination
    }
    Hanoi(n-1,src,dest,mid);//First move n-1 plates from src to mid
    cout << src << "->" << dest << endl;
    //Move another plate from src to dest
    Hanoi(n-1,mid,src,dest);//Compare the previous operation, and finally move a plate from mid to dest
    return ;
}
int main()
{
    int n;
    cin >> n;
    Hanoi(n,'A','B','C');
    return 0;
}

Conclusion:

  1. Understanding problems
    The last step can not directly move all plates from mid to dest, but try to move n-1 plates to the top of nth plate of DeST by imitating the previous src operation of moving plates from mid to dest.

Example 3: Queen n's question

Description:
Input the integer n, and ask n chess queens to put them on n*n chessboard. They can't attack each other, and output all schemes.

Input example:

4

Output example:

2 4 1 3
3 1 4 2

Solutions:

  1. Queens cannot be in the same column, row, or diagonal position.

Code:

#include <iostream>
#include <cmath>
using namespace std;
int N;
int queenPos[100];
//Used to store the calculated Queen's position. The top left corner is (0, 0)
void NQueen(int k);
int main()
{
    cin >> N;
    NQueen(0);//Put the queen on line 0
	return 0;
}

void NQueen(int k)//0~k-1 lines are all set
{
    int i;
    if(k == N) {//All set up.
        for(i = 0 ; i < N; i++)
          cout << queenPos[i] + 1 << " ";
        cout << endl;
        return ;//NQueen(4) terminate, open the next possible cycle 
    }
    
    for(i = 0; i < N; i++){//Position the k queen one by one
        int j;
        for(j = 0; j < k; j++){
            //Compare with the positions of the k queens that have been arranged to see if there is any conflict
            if(queenPos[j] == i || abs(queenPos[j] - i) == abs(k - j)){//Functions in cmath header file
                break;
            }
        }
        if(j == k){
            queenPos[k] = i;//Parameter k is best used
            //Cout < < queenpos ["< K <"] = "< I < < endl; observe the execution process
            NQueen(k+1);
        }
    }//for(i = 0; i < N; i++)
    
    
}
/*
4
queenPos[0]=0
queenPos[1]=2
0 2 fail 
queenPos[1]=3
queenPos[2]=1
0 3 1 fail 
queenPos[0]=1
queenPos[1]=3
queenPos[2]=0
queenPos[3]=2
1 3 0 2 Success, print + 1 
2 4 1 3
queenPos[0]=2
queenPos[1]=0
queenPos[2]=3
queenPos[3]=1
2 0 3 1 Success, print + 1
3 1 4 2
queenPos[0]=3
queenPos[1]=0
queenPos[2]=2
3 0 2 fail
queenPos[1]=1
3 1 fail
*/

Conclusion:

  1. Grammatical problems
    The value of j from the for loop can be applied outside the loop (if j is defined outside the loop).
  2. Understanding problems
    abs function is used to calculate the absolute value. It is known that it cannot be on the same diagonal, that is, the slope is not 1. Therefore, abs(y1-y2) == abs(x1-x2), that is, abs(queenPos[j]-i) == abs(k-j).

Example 4: inverse Polish expression

Description:
Inverse Polish is a kind of arithmetic expression which precedes operators. It has the advantage that there is no priority relationship between operators and no need to change the operation order with parentheses.

Input:
The input is a line, where the operators and operands are separated by spaces

Output:
Output as one line, value of expression

Input example:

* + 11.0 12.0 + 24.0 35.0 

Output example:

1357.000000

Tips: (11.0 + 12.0) * (24.0 + 35.0)

Solutions:

  1. Definition of inverse Polish expression:
    1) A number is an inverse Polish expression whose value is
    2) Operator inverse Polish expression inverse Polish expression is an inverse Polish expression. Value is the result of the value operation of two inverse Polish expressions
  2. Using recursion to solve the problem of recursion form

Code:

#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;

double exp()
{//Read in an inverse Polish expression and calculate its value
    char s[20];
    cin >> s;
    switch(s[0]) {
        case '+': return exp() + exp();
        case '-': return exp() - exp();
        case '*': return exp() * exp();
        case '/': return exp() / exp();
        default: return atof(s);//Function of cstlib header file to convert string to double type
        break;
    }
}
int main()
{
    printf("%lf",exp());//Functions of stdio header file
    return 0;
}

Conclusion:

  1. Grammatical problems
    1) For input, float uses% f, double uses% lf; for output, both float and double use% f.
    2) As the name implies, default is the default case, and it will only be executed if any conditions do not match, so the default statement is placed after the end of all cases.

After class exercise 1: full arrangement

Description:
Given a string of different lowercase letters, output all the permutations of the string. Let's assume that for lowercase letters, there are 'a' < b '< b' < b '< a' < b '< b' < b '< b' < b '< b' < b '< b' < b '< b' < b '< b' < b ' < y '< z', and the letters in the given string have been arranged from the smallest to the largest.

Input:
The input has only one line, which is a string composed of different lowercase letters. It is known that the length of the string is between 1 and 6.

Output:
Output all permutations of this string, one per line. Require a smaller alphabetical order at the front.

Sample input:

abc

Sample output:

abc
acb
bac
bca
cab
cba

Code:

#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;
const int M = 8;//Keep code clean
char str[M];//Input string
char permutation[M];//Permutation results
bool used[M] = {0};
int L = 0;
void Permutation(int n)
{	
	if( n == L ) {
		permutation[L] = 0;
		cout << permutation << endl;
		return ;
	}

	for(int i = 0;i < L; ++i) {
		if( !used[i]) {
			used[i] = true;//Ensure that the location is not modified during recursion
			permutation[n] = str[i];
            //Cout < < p ["< n <"] = "< permutation [n] < endl; observe the execution process
			Permutation(n+1);
			used[i] = false;//After a recursion, let go of the usage right
		}
	}
}

int main()
{
	cin >> str;
	L = strlen(str);//The function of cstring
	sort(str,str+L);
	Permutation(0);
	return 0;	
}
/*
p[0]=a
p[1]=b
p[2]=c
abc
p[1]=c
p[2]=b
acb
p[0]=b
p[1]=a
p[2]=c
bac
p[1]=c
p[2]=a
bca
p[0]=c
p[1]=a
p[2]=b
cab
p[1]=b
p[2]=a
cba
*/

Conclusion:

  1. Grammatical problems
    1)sort(first_pointer,first_pointer+n,cmp)
    Used for array, list, vector sorting. Parameter 1 indicates that the first parameter is the first address of the array, and parameter 2 indicates the first address plus the length n of the array (representing the next address of the last address). Parameter 3 can be left blank and is in ascending order by default. To use this function, you need to first include the algorithm header file.
    2) String is a C + + standard library header file for string operations. cstring is the C + + standard library version of the C standard library header file string.h, which contains the declaration of some types and functions related to C-style strings (NUL is' \ 0 'end string), such as strcmp, strchr, strstr str, etc.
  2. Understanding problems
    1) Return ends with recursion, not the whole program. At the end of the recursion, return to the previous level of recursion.
    2) Pay attention to the importance of used [] in the program, and do not miss it.
    3) Details, such as setting L as a global variable, arranging the input array first, p[L]=0, etc.

After class exercise 2: Power

Description:
Any positive integer can be expressed by the power of 2. For example:

137=2^7+2^3+2^0

At the same time, the agreed square is expressed in brackets, that is, a B can be expressed as a(b). Thus, 137 can be expressed as:

2(7)+2(3)+2(0)

Further: 7 = 22 + 2 + 20 (21 is represented by 2)

    3=2+2^0

So the last 137 can be expressed as:

2(2(2)+2+2(0))+2(2+2(0))+2(0)

Another example is:

1315=2^10+2^8+2^5+2+2^0

So 1315 can be expressed as:

2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)

Input:
A positive integer n (n ≤ 20000).

Output:
One line, 0, 2 of n according to the Convention (no space in the representation).

Sample input:

137

Sample output:

2(2(2)+2+2(0))+2(2+2(0))+2(0)

Code:

#include <iostream>
using namespace std;
inline int GetBit(int n,int i)
{
	return (n >> i ) & 1;
}

void Print(int n) {
	bool first = true;
	for(int i = 15; i >= 0; --i) {
		if( GetBit(n,i)) {
			if(! first ) {
				cout << "+" ;
			}
			else 
				first = false;

			if( i == 0)
				cout << "2(0)" ;
			else if( i == 1)
			 	cout << "2";
			else {
				cout << "2(";
				Print(i);
				cout << ")";
			}
		}

	}
}

int main()
{
	int n;
	cin >> n; 
	Print(n);
	return 0;
}

Conclusion:

  1. Understanding problems
    1) Note that the reduction is continued until the power is 0, 1, and the recursion ends.
    2) It is easy to use bit operation.
    3) Pay attention to the conditions that "+" meets.

(n,i)) {
if(! first ) {
cout << "+" ;
}
else
first = false;

		if( i == 0)
			cout << "2(0)" ;
		else if( i == 1)
		 	cout << "2";
		else {
			cout << "2(";
			Print(i);
			cout << ")";
		}
	}

}

}

int main()
{
int n;
cin >> n;
Print(n);
return 0;
}

**Summary:**
1. Understand the problem
 1) Note that the reduction is continued until the power is 0, 1, and the recursion ends.
2) It is easy to use bit operation.
3) Pay attention to the conditions that "+" meets.

Published 2 original articles, won praise 1, visited 26
Private letter follow

Posted by jandrox_ox on Thu, 12 Mar 2020 03:24:03 -0700