Problem-solving report-2017 C/C++ Group A fifth question letter string (recursive)

Title description:

Many strings can be formed by the three letters of A, B, and C.
For example: "A", "AB", "ABC", "ABA", "AACBB" ...

Now, Xiao Ming is thinking about a question:
If the number of each letter is limited, how many strings of known length can be formed ?

He asked good friends to help, and quickly got the code. The
solution was super simple, but the most important part was unclear.

Please carefully analyze the source code and fill in the missing content in the underlined part.

For the above test data, the result of Xiaoming's oral calculation should be:
6
19


Analysis and solution

A simple, rude and effective way to fill in the blanks of the Blue Bridge Cup code is: try it blindly. Sometimes, just try it out.

Most of the code in the Blue Bridge Cup is recursive or backtracking, and it often gives us the results of a few examples. The recursive code is nothing more than that, and it comes out after a few more attempts.

For this question:

When does n change from i to i+1? There must be one more letter used in the string. This letter can be a, b, or c.

Therefore, the three possibilities are added together and the result comes out.

That is:

#include <stdio.h>

// a个A,b个B,c个C 字母,能组成多少个不同的长度为n的串。
int f(int a, int b, int c, int n)
{
    
    
	if(a<0 || b<0 || c<0) return 0;
	if(n==0) return 1; 
	
	return f(a-1,b,c,n-1)+f(a,b-1,c,n-1)+f(a,b,c-1,n-1) ;  // 填空
}

int main()
{
    
    
	printf("%d\n", f(1,1,1,2));
	printf("%d\n", f(1,2,3,3));
	return 0;
}

PS: I was tortured by the first four questions. . Seeing this question seems to see the dawn. .


A good sentence to share and encourage each other:
only practice one day's work a day, and don't practice ten-day sky a day.

Guess you like

Origin blog.csdn.net/weixin_43899069/article/details/108897116