#include <vector>
#include <string>
using namespace std;
int answer = 0;
void DFS(int sum, int index, int target, vector<int> *numbers){
if(index == (*numbers).size()){
if(sum == target) answer++;
return;
}
DFS(sum + (*numbers)[index], index + 1, target, numbers);
DFS(sum - (*numbers)[index], index + 1, target, numbers);
}
int solution(vector<int> numbers, int target) {
DFS(0, 0, target, &numbers);
return answer;
}
#include <stdio.h>
#include <vector>
using namespace std;
int answer = 0;
void DFS(int sum, int index, int target, vector<int> *numbers){
if(index == (*numbers).size()){
if(sum == target) answer++;
return;
}
DFS(sum + (*numbers)[index], index + 1, target, numbers);
DFS(sum - (*numbers)[index], index + 1, target, numbers);
}
int solution(vector<int> numbers, int target) {
DFS(0, 0, target, &numbers);
return answer;
}
int main(){
vector<int> number;
int n;
scanf("%d", &n);
for(int i=0; i<n; i++){
int num;
scanf("%d", &num);
number.push_back(num);
}
int target;
scanf("%d", &target);
printf("# of target: %d\n", solution(number, target));
}
index๊ฐ number.size()๋ผ๋ ๊ฒ์ 5๊ฐ์ ๋ชจ๋ ์์๋ฅผ sum์ ๋ํ ๊ฒ์ด๊ณ , ์ด ๊ฒฐ๊ณผ๋ฅผ target๊ณผ ๋น๊ตํ์ฌ ๊ฐ์ผ๋ฉด answer์ 1 ์ฆ๊ฐ์ํจ๋ค.
DFS(0, 0)
{
DFS(sum+num[0], 1)
{
DFS(sum+num[1], 2)
{
DFS(sum+num[2], 3)
{
DFS(sum+num[3], 4)
{
DFS(sum+num[4], 5)
{
if(5 == num.size()) return;
}
DFS(sum-num[4], 5)
{
if(5 == num.size()) return;
}
}
DFS(sum-num[3]), 4)
{
DFS(sum+num[4]), 5)
{
}
DFS(sum-num[4]), 5)
{
}
}
...
...
์ฌ๊ทํธ์ถ์ ๊ฒฝ์ฐ, ์์ ๊ฐ์ ๊ณผ์ ์ผ๋ก ํจ์๋ฅผ ํธ์ถํ๊ณ ์์ ์ ๋ถ๋ ๋ ํจ์๋ก ๋ฆฌํดํ๋ ๊ณผ์ ์ ๋ฐ๋ณตํ๋ค. DFS(0,0)์์ ๋ง์ง๋ง์ผ๋ก DFS(sum-num[0], 1)์ ๋๋ด๋ฉด DFS(0,0)๊ฐ ์์ ์ ํธ์ถํ main ํจ์๋ก ๋ฆฌํดํ์ฌ ๋น๋ก์ ์ฌ๊ท๋ฅผ ๋๋ผ ์ ์๊ฒ ๋๋ค.
[+1, +1, +1, +1, +1]
[+1, +1, +1, +1, -1]
[+1, +1, +1, -1, +1]
[+1, +1, +1, -1, -1]
[+1, +1, -1, +1, +1]
[+1, +1, -1, +1, -1]
[+1, +1, -1, -1, +1]
[+1, +1, -1, -1, -1]
[+1, -1, +1, +1, +1]
[+1, -1, +1, +1, -1]
[+1, -1, +1, -1, +1]
[+1, -1, +1, -1, -1]
[+1, -1, -1, +1, +1]
[+1, -1, -1, +1, -1]
[+1, -1, -1, -1, +1]
[+1, -1, -1, -1, -1]
[-1, +1, +1, +1, +1]
[-1, +1, +1, +1, -1]
[-1, +1, +1, -1, +1]
[-1, +1, +1, -1, -1]
[-1, +1, -1, +1, +1]
[-1, +1, -1, +1, -1]
[-1, +1, -1, -1, +1]
[-1, +1, -1, -1, -1]
[-1, +1, -1, -1, -1]
[-1, -1, +1, +1, +1]
[-1, -1, +1, +1, -1]
[-1, -1, +1, -1, +1]
[-1, -1, +1, -1, -1]
[-1, -1, -1, +1, +1]
[-1, -1, -1, +1, -1]
[-1, -1, -1, -1, +1]
[-1, -1, -1, -1, -1]
์์์ ๊ฐ์๊ฐ 5๊ฐ์ธ ๊ฒฝ์ฐ, ์์ ๊ฐ์ ๋ ธ๋ ํ์ ์์๋ฅผ ๊ฐ๋๋ค.
[๋ฐฑ์ค(BOJ)] 2644๋ฒ: ์ด์๊ณ์ฐ (DFS/BFS, C++) (0) | 2021.02.08 |
---|---|
[๋ฐฑ์ค(BOJ)] 1182๋ฒ: ๋ถ๋ถ์์ด์ ํฉ (๋ฐฑํธ๋ํน(Backtracking), C++) (0) | 2021.02.05 |
[๋ฐฑ์ค(BOJ)] 1620๋ฒ: ๋๋์ผ ํฌ์ผ๋ชฌ ๋ง์คํฐ ์ด๋ค์ (Hash, C++) (0) | 2021.01.29 |
[๋ฐฑ์ค(BOJ)] 1260๋ฒ: DFS์ BFS (C++) (0) | 2021.01.22 |
[๋ฐฑ์ค(BOJ)] 3273๋ฒ: ๋ ์์ ํฉ (Two Pointers Algorithm, C++) (0) | 2021.01.22 |