Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- C++
- 백준
- 깊이우선탐색
- 우선순위큐
- BFS
- 알고리즘
- 유클리드호제법
- 문자열
- 정렬
- 오블완
- stoi
- 티스토리챌린지
- Set
- int
- N과M
- 다이나믹프로그래밍
- vector
- DP
- 프로그래머스
- map
- Sort
- 배열
- 분할정복
- DFS
- 그래프
- 최소공배수
- 백트래킹
- 이분탐색
- priority_queue
- 에라토스테네스의 체
Archives
- Today
- Total
안녕 세상아,
[프로그래머스/c++] Lv2 타겟 넘버 본문
https://school.programmers.co.kr/learn/courses/30/lessons/43165
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
dfs를 사용하는 문제이다.
n개의 정수가 주어지고 각 정수는 +, - 배치에 따라 값이 달라진다. n개의 정수가 주어질 때 경우의 수는 2의 n승이다.
각 값이 +,-에 따라 달라지기 때문에 깊이 우선 탐색을 하면 값을 구할 수 있다. 계속 반복해야되기 때문에 재귀를 사용한다는 것을 안다면 dfs 사용하는 문제라는 것을 빠르게 알 수 있다.
#include <string>
#include <vector>
using namespace std;
//dfs
void dfs(vector<int> numbers, int target, int& answer, int count = 0, int sum = 0) {
//dfs 끝까지 왔을 때, answer 출력
if (count == numbers.size() - 1) {
if (target == sum + numbers[count])
answer++;
if (target == sum - numbers[count])
answer++;
return;
}
//+, - 둘 다 깊이 우선 탐색 해줌
dfs(numbers, target, answer, count + 1, sum - numbers[count]);
dfs(numbers, target, answer, count + 1, sum + numbers[count]);
}
int solution(vector<int> numbers, int target) {
int answer = 0;
dfs(numbers, target, answer);
return answer;
}
'프로그래머스' 카테고리의 다른 글
[프로그래머스/c++] Lv1 옹알이(2) (0) | 2025.01.04 |
---|---|
[프로그래머스/c++] Lv2 [1차] 뉴스 클러스터링 (vector 사용) (0) | 2024.12.17 |
[프로그래머스/c++] Lv2 튜플 (1) | 2024.12.15 |
[프로그래머스/c++] Lv2 게임 맵 최단거리 (1) | 2024.11.15 |
[프로그래머스/c++] Lv1 덧칠하기 (0) | 2024.11.06 |