๐Ÿ“ Coding Test Study/C++

[10์ฃผ ์™„์„ฑ C++ ์ฝ”๋”ฉํ…Œ์ŠคํŠธ] ํ•„์ˆ˜๊ฐœ๋… - ์žฌ๊ท€ํ•จ์ˆ˜(Recursion)

ibelieveinme 2023. 8. 3. 17:15
728x90

* ์žฌ๊ท€ํ•จ์ˆ˜

1) ์ •์˜ ๋‹จ๊ณ„์—์„œ ์ž์‹ ์„ ์ฐธ์กฐํ•˜๋Š” ํ•จ์ˆ˜

2) ์ „๋‹ฌ๋˜๋Š” ์ƒํƒœ์ธ ๋งค๊ฐœ๋ณ€์ˆ˜๊ฐ€ ๋‹ฌ๋ผ์งˆ ๋ฟ ๋˜‘๊ฐ™์€ ์ผ์„ ํ•˜๋Š” ํ•จ์ˆ˜

3) ํฐ ๋ฌธ์ œ๋ฅผ ์ž‘์€ ๋ฌธ์ œ๋กœ ์ชผ๊ฐค ๋•Œ ์‚ฌ์šฉํ•จ

 

* ์žฌ๊ท€ํ•จ์ˆ˜ ์ฃผ์˜์‚ฌํ•ญ

1) ๋ฐ˜๋“œ์‹œ ๊ธฐ์ €์‚ฌ๋ก€๋ฅผ ์จ์•ผ ํ•œ๋‹ค.(์ข…๋ฃŒ์กฐ๊ฑด)

2) ์‚ฌ์ดํด์ด ์žˆ๋‹ค๋ฉด ์“ฐ๋ฉด ์•ˆ๋œ๋‹ค.

3) ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ๋  ๊ฒƒ ๊ฐ™์œผ๋ฉด ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ.(ํ•จ์ˆ˜ ํ˜ธ์ถœ์— ๋Œ€ํ•œ cost๋ฅผ ์ค„์ด๊ธฐ ์œ„ํ•ด. ๋ฐ˜๋ณต๋ฌธ์ด ๋” ๋น ๋ฅผ ์ˆ˜ ์žˆ์Œ.)

 

* ์˜ˆ์‹œ

1) ํŒฉํ† ๋ฆฌ์–ผ n! : ๊ทธ ์ด์ „์˜ ํ•ญ์„ ๋ชจ๋‘ ๊ณฑํ•˜๋Š” ๊ฒƒ.

2) ํ”ผ๋ณด๋‚˜์น˜: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ...

#include <bits/stdc++.h>
using namespace std; 

int fact(int n){
    if(n == 1 || n == 0) return 1;
    return n* fact(n -1);
}

int fibo(int n){
    if(n == 0 || n == 1) return n;
    return fibo(n - 1) + fibo(n - 2);
}

int n = 5;
int main() { 
    cout << fact(5) << "\n";
    cout << fibo(5) << "\n";
    return 0; 
}

์ ํ™”์‹์„ ๊ธฐ๋ฐ˜์œผ๋กœ ๊ตฌํ˜„ํ•œ ๋ชจ์Šต !

 

์ถœ๋ ฅ

120

5

 

#include <bits/stdc++.h>
using namespace std; 

int fact(int n) {
    int result = 1;
    for(int i = n; i >= 1; i--) {
        result *= i;
    }
    return result;
}

int n = 5;
int main() { 
    cout << fact(5) << "\n";
    return 0; 
}

์ด ๋•Œ, ์žฌ๊ท€ํ•จ์ˆ˜๋Š” ํ•จ์ˆ˜ ํ˜ธ์ถœ์— ๋Œ€ํ•œ cost ๊ฐ€ ์žˆ์œผ๋ฏ€๋กœ ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ๊ตฌํ˜„ ๊ฐ€๋Šฅํ•˜๋ฉด ์œ„์ฒ˜๋Ÿผ ๊ตฌํ˜„ํ•˜๊ธฐ.

 

์ถœ๋ ฅ

120

 

728x90