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 |
Tags
- c#
- 스택의 특징
- 게리멘더링2
- 백준 17779
- 자료구조
- 백준
- Stack 이란
- dfs
- 1764
- 백준 5397
- 백준 1158
- AVL 시간 복잡도
- 해시구현
- 백준 17471
- 버킷 정렬
- 백준 1406
- ㅣ풀이
- heap
- 풀이
- 해시 구현
- 조세퍼스 순열
- 백준 2447
- 별 찍기 10
- 백준 17822
- 구현
- qorwns
- C/C++ 구현
- 시간 복잡도
- 원판 돌리기
- 5397
Archives
- Today
- Total
홍시홍의 프로그래밍
[프로그래머스] 타겟 넘버 본문
분류 : bfs/dfs
요구사항
주어진 숫자들과 +, - 연산을 이용하여 target 숫자 만들기
풀이
bfs로 풀어보았다.
position과 sum을 index로 가지는 큐를 만들어서
현재 position의 값을 +, - 해준뒤 position을 하나 증가시켜 큐에 넣어서 풀었다
#include <string>
#include <vector>
#include <queue>
#include <iostream>
using namespace std;
struct go {
int pos;
int sum;
};
int solution(vector<int> numbers, int target) {
int answer = 0;
queue<go> q;
int lastpos = numbers.size();
q.push({ 0,0 });
while (!q.empty()) {
int nowpos = q.front().pos;
int nowsum = q.front().sum;
q.pop();
if (nowpos == lastpos && nowsum == target) {
answer++;
continue;
}
if (nowpos == lastpos) {
continue;
}
for (int i = 0; i < 2; i++) {
int nextsum;
if (i == 0) {
nextsum = nowsum + numbers[nowpos];
}
else if (i == 1) {
nextsum = nowsum - numbers[nowpos];
}
q.push({ nowpos + 1,nextsum });
}
}
return answer;
}
'알고리즘 문제풀이 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] 단어 변화 (0) | 2020.04.12 |
---|---|
[프로그래머스] 네트워크 (0) | 2020.04.10 |
[프로그래머스] 베스트앨범 (0) | 2020.04.10 |
[프로그래머스] 멀쩡한 사각형 (0) | 2020.04.05 |
[프로그래머스] 쇠막대기 (0) | 2020.04.03 |
Comments