티스토리 뷰
https://www.acmicpc.net/problem/1182
1182번: 부분수열의 합
첫째 줄에 정수의 개수를 나타내는 N과 정수 S가 주어진다. (1 ≤ N ≤ 20, |S| ≤ 1,000,000) 둘째 줄에 N개의 정수가 빈 칸을 사이에 두고 주어진다. 주어지는 정수의 절댓값은 100,000을 넘지 않는다.
www.acmicpc.net
input
- N : 수열의 갯수
- S : 부분수열의 합이 되어야 할 값
- number : 수열
output
- 부분수열과 S가 일치하는 갯수를 반환.
solution
- dfs
- 수열 number와 S, 수열의 index인 idx와 수열의 합으로 next를 넘겨준다.
- idx를 증가시키며 호출한다.
- next와 현대 index의 수를 합하며 recursion 호출 한다.
- 수열의 길이와 index가 같아지면 함수를 return
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int c = 0;
void recursion(vector<int>& number, int S, int idx, int next) {
if (number.size() == idx) return;
if (next + number[idx] == S) c++;
recursion(number, S, idx + 1, next);
recursion(number, S, idx + 1, next + number[idx]);
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int N, S, inputNum;
vector<int> number;
cin >> N >> S;
for (int i = 0; i < N; i++) {
cin >> inputNum;
number.push_back(inputNum);
}
recursion(number, S, 0, 0);
cout << c << "\n";
return 0;
}
time complexity : O(n²)
space complexity : O(n)
'알고리즘 문제 풀이' 카테고리의 다른 글
[알고리즘문제] 릿코드 Find First and Last Position of Element in Sorted Array (0) | 2021.10.11 |
---|---|
[알고리즘문제] 릿코드 Find Kth Bit in Nth Binary String (0) | 2021.09.25 |
[알고리즘문제] 백준 단어나누기 (0) | 2021.08.24 |
[알고리즘문제] 백준 9012 괄호 (0) | 2021.08.15 |
[알고리즘문제] 릿코드 Pascal's Triangle (0) | 2021.07.10 |