Algorithm/Baekjoon
[Algorithm]Baekjoon 1182번 : 부분수열의 합
MaxLevel
2022. 7. 17. 23:48
https://www.acmicpc.net/problem/1182
1182번: 부분수열의 합
첫째 줄에 정수의 개수를 나타내는 N과 정수 S가 주어진다. (1 ≤ N ≤ 20, |S| ≤ 1,000,000) 둘째 줄에 N개의 정수가 빈 칸을 사이에 두고 주어진다. 주어지는 정수의 절댓값은 100,000을 넘지 않는다.
www.acmicpc.net
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
#include <math.h>
#include <queue>
#include <functional>
#include <sstream>
using namespace std;
int answer = 0;
int target = 0;
int maxSize = 0;
void solution(int index, int sum, vector<int>& numbers)
{
int before = sum;
sum += numbers[index];
if (sum == target) answer++;
if (index+1 <= maxSize - 1)
{
solution(index+1, before, numbers);
solution(index+1, sum, numbers);
}
else return;
}
int main()
{
int n = 0;
int s = 0;
int input = 0;
vector<int> numbers;
cin >> n >> s;
target = s;
maxSize = n;
for (int i = 0; i < n; i++)
{
cin >> input;
numbers.push_back(input);
}
solution(0, 0, numbers);
// N은 1이상 20이하
// S는 절대값 1000,000 이하.
cout << answer;
}
|
cs |
백트래킹 기본예제 중 하나인 부분수열의 합 문제다.
백트래킹은 완전탐색을 할 때, 조건에 따라 더이상 탐색을 진행하지않고 다시 되돌아가는 것을 의미한다.
그렇기 때문에 되돌아가는 조건을 잘 설정하는게 관건이고 성능에 큰 영향을 미칠것이다.