CS 32 Lecture 8. Recursion
아래의 글은 제가 재학중인 UCLA의 CS 32: Data Structures의 렉쳐를 들으며 작성하는 글입니다.
📝 Recursion
Rules
- Every recursive function must have a stopping condition (base case).
- Recursive functions should never use global, static, or member variables. They should only use local variables and parameters.
Steps
1. Write the function header.
Figure out what arguments your function will take and what it needs to return.
2. Define your magic function.
Magic function here shows logic behind the recursive function. Before making a recursive function right away, write magic function.
3. Add your base case code.
There might be multiple base cases for a function depending on what it does.
4. Solve the problem by using the magic function.
Divide the problem into sub parts and arrange what the magic function returns
5. Remove the magic function.
6. Validate function with the simplest possible input, then more complex inputs.
Class Challenge
printArr
void printArr(int arr[], int size)
{
if (size == 0)
cout << *arr << "\n";
printArr(arr+1, size-1);
}
reversePrint
void reversePrint(string arr[], int size)
{
if (size == 0)
cout << arr[0] << "\n";
reversePrint(arr+1, size-1);
}
Recursion with Linked List
Tips
- Every recursive function must have a stopping condition (base case).
- Recursive functions should never use global, static, or member variables. They should only use local variables and parameters.
1. Write the function header.
Figure out what arguments your function will take and what it needs to return.
2. Define your magic function.
Magic function here shows logic behind the recursive function. Before making a recursive function right away, write magic function.
3. Add your base case code.
There might be multiple base cases for a function depending on what it does.
4. Solve the problem by using the magic function.
Divide the problem into sub parts and arrange what the magic function returns
5. Remove the magic function.
6. Validate function with the simplest possible input, then more complex inputs.
printArr
void printArr(int arr[], int size)
{
if (size == 0)
cout << *arr << "\n";
printArr(arr+1, size-1);
}
reversePrint
void reversePrint(string arr[], int size)
{
if (size == 0)
cout << arr[0] << "\n";
reversePrint(arr+1, size-1);
}
Recursion with Linked List
Tips
Your recursive function should generally only access the current node/array cell passed into it.
Your recursive function should rarely/never access the values in the node/cell below it.
Author And Source
이 문제에 관하여(CS 32 Lecture 8. Recursion), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@hojin11choi/Lecture-8.-Recursion저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)