Recursion: grasp the core recursive method

Recursive My understanding is that
the method or function calls itself is called a recursive
1. broken down into: + a small amount of direct questions
2. classified as: small-scale problems
Here Insert Picture Description
in order to calculate f (10), you need to know f (9), count f (9) needs to be calculated f (8)
features:
1. their calls itself
2. to avoid an infinite loop
method:
1. find repeated (subproblems find more small-scale (and with the same form of the original problem); factorial of n - , first find the factorial .... n-1)
2. Get change (change in which things, seeking the factorial of n, n-1 first seek factorial, .... change amount as a parameter)
3 looking boundary (loop termination condition is determined outlet, find the factorial of n, it has been changed to find a recursive factorial, time to 1, 1 to 1 factorial, returns)
a, n factorial seeking
seeking the factorial of n, first n-1 factorial seek

#include<iostream>  
using namespace std;   

int f(int){
	int n;
	if(n==1)   //当n=1的时候,条件终止
	return 1;
	else 
	return n*f(n-1)   //求n-1的阶乘,再次缩小变为n-1*n-2,n就会越来越小
}   

Second, print ij

#include<iostream>
using namespace std;

static void f(int i,int j){    //i为变量,j作为终点不变
if(i>j)  //为出口;终止
return;
cout<<i<<endl;  //打印i
f(i+1,j);   //i+1越靠近j,离j越来越近
}  
int main(){
	f(1,10);  
}

Third, find the array and
1. Find duplicate, arr into the small-scale, out of the first division, the rest to the recursive been so repeat
2. look for changes in the length of the array changes, changing the starting point , in the narrow range of the array, end unchanged
3. find the boundary, it is the length of the array

#include<iostream>
using namespace std;

static int f(int arr[],int begin ){  //begin初始数组
	if (begin==arr.length-1){
		return arr[begin];
	}
	return arr[begin]+f(arr,begin+1);   //
}
int main(){
	int res=f(new int[]{1,2,3,4,5},begin 0);
	cout<<res<<endl; 
} 

Fourth, reverse text
after inversion becomes dcba abcd
Here Insert Picture Description
and so finally b splicing a
variable: the change as the end point, to the beginning of the time varying termination

#include<iostream>
#include<cstring> 
#include<algorithm>
#include<vector>
using namespace std;

static String res(String src,int end){
	if(end==0)
	{
		return ""+src.charAt(0);
	}
	return src.charAt(end)+res(src,end-1);
}
int main(){
	cout<<res<<endl;
	cout<<(res("abcd",3))<<endl;;
}
Published 71 original articles · won praise 4 · views 10000 +

Guess you like

Origin blog.csdn.net/gl620321/article/details/104378881