문제 설명
n개의 음이 아닌 정수가 있습니다. 이 수를 적절히 더하거나 빼서 타겟 넘버를 만들려고 합니다. 예를 들어 [1, 1, 1, 1, 1]로 숫자 3을 만들려면 다음 다섯 방법을 쓸 수 있습니다.
-1+1+1+1+1 = 3 +1-1+1+1+1 = 3 +1+1-1+1+1 = 3 +1+1+1-1+1 = 3 +1+1+1+1-1 = 3
사용할 수 있는 숫자가 담긴 배열 numbers, 타겟 넘버 target이 매개변수로 주어질 때 숫자를 적절히 더하고 빼서 타겟 넘버를 만드는 방법의 수를 return 하도록 solution 함수를 작성해주세요.
제한사항
- 주어지는 숫자의 개수는 2개 이상 20개 이하입니다.
- 각 숫자는 1 이상 50 이하인 자연수입니다.
- 타겟 넘버는 1 이상 1000 이하인 자연수입니다.
풀이
다른 사람들의 풀이를 보니까 내 풀이는 너무 복잡한 것 같다. 방법을 개선시켜야 하는데 도무지 어떻게 개선시켜야할지 생각이 나지 않는다.
#include <string>
#include <vector>
#include <queue>
using namespace std;
int pm[2] = {-1, 1};
int answer = 0;
void bfs(int start, vector<int> numbers, int target) {
int num = 1, max = start;
int size = numbers.size();
queue<int>need_visit;
need_visit.push(start);
while(num != size) {
int node = need_visit.front();
need_visit.pop();
for(int i=0; i<2; i++) {
int new_node = node + (numbers[num] * pm[i]);
need_visit.push(new_node);
if(num == size - 1 && target == new_node)
answer++;
}
if(node == max) {
max = node + (numbers[num] * pm[1]);
num++;
}
}
}
int solution(vector<int> numbers, int target) {
bfs(numbers[0], numbers, target);
bfs(-numbers[0], numbers, target);
return answer;
}
'알고리즘 > 프로그래머스 문제풀이' 카테고리의 다른 글
[프로그래머스] 모의고사 / C++ (0) | 2020.08.25 |
---|---|
[프로그래머스] 네트워크 / C++ (0) | 2020.08.25 |
[프로그래머스] 정렬 / H-Index (0) | 2020.08.25 |
[프로그래머스] 스택,큐 / 프린터 (0) | 2020.08.24 |
[프로그래머스] 기능개발 / C++ (0) | 2020.08.24 |