爲了更好地理解遞歸,我試圖計算每對(),( )之間有多少個字符,而不包括其他()中的字符。例如:試圖理解遞歸函數
(abc(ab(abc)cd)(()ab))
將輸出:
Level 3: 3
Level 2: 4
Level 3: 0
Level 2: 2
Level 1: 3
這裏的 「級別」 是指()嵌套的水平。因此,三級意味着角色在一對(3)內的一對(2)內的一對(1)內。
要做到這一點,我的猜測是最簡單的做法是實現對函數的某種遞歸調用,如函數「recursiveParaCheck」中的註釋。我開始考慮重現關係時,我的方法是什麼?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int recursiveParaCheck(char input[], int startPos, int level);
void main()
{
char input[] = "";
char notDone = 'Y';
do
{
//Read in input
printf("Please enter input: ");
scanf(" %s", input);
//Call Recursive Function to print out desired information
recursiveParaCheck(input, 1, 1);
printf("\n Would you like to try again? Y/N: ");
scanf(" %c", ¬Done);
notDone = toupper(notDone);
}while(notDone == 'Y');
}
int recursiveParaCheck(char input[], int startPos, int level)
{
int pos = startPos;
int total = 0;
do
{
if(input[pos] != '(' && input[pos] != ')')
{
++total;
}
//What is the base case?
if(BASE CASE)
{
//Do something?
}
//When do I need to make a recursive call?
if(SITUATION WHERE I MAKE RECURSIVE CALL)
{
//Do something?
}
++pos;
}while(pos < 1000000); // assuming my input will not be this long
}
感謝發佈https://community.topcoder.com/tc?module=Static&d1=tutorials&d2=recursionPt1但我知道遞歸是什麼 – user3517150