프로그래머스(C++) - 타겟 넘버

2025. 9. 13. 16:01·C++ 프로그래머스 다이어리/BFS , DFS

●문제

 

●입출력

 

문제해석 : numbers에 있는 숫자들로 더하거나 빼서 target숫자를 만들수있는 경우의수를 return

푼방법 : dfs 재귀함수를 사용하여 ind 현재 처리중인 숫자 인덱스와 dfsSum 누적 합을 매개변수로 가지고 계산

주의할점 : 문제에서 주어진 numbers는 vector이니 그냥 값을 dfs에서 복사하면 너무 많이 복사하니

vector<int>numbers는 &참조로 가져오고 int같은 작은 변수값은 그대로 복사해도 무방

#include <string>
#include <vector>
#include <iostream>

using namespace std;

int answer = 0;
//ind -> 몇번째 숫자를 처리중인가 , dfsSum -> 누적 합
void DFS(int ind, vector<int>& numbers, int target, int dfsSum)
{
	//재귀함수 멈추는 조건 ( numbers의 모든 원소를 다 썻을때 )
	if (ind == numbers.size())
	{
		if (dfsSum == target) answer++;
		return;
	}

	DFS(ind + 1, numbers, target, dfsSum + numbers[ind]);
	DFS(ind + 1, numbers, target, dfsSum - numbers[ind]);
}
int solution(vector<int> numbers, int target)
{
	DFS(0, numbers, target, 0);
	return answer;
}


int main(void)
{
	vector<int> numbers = { 1, 1, 1, 1, 1 };
	int target = 3;
	int result = solution(numbers, target);
	cout << result << " ";
}

 

레벨 : 2 

점수 : 1

'C++ 프로그래머스 다이어리 > BFS , DFS' 카테고리의 다른 글

프로그래머스(C++) - 여행경로  (0) 2025.10.05
프로그래머스(C++) - 단어 변환  (0) 2025.09.23
프로그래머스(C++) - 게임 맵 최단거리  (0) 2025.09.14
프로그래머스(C++) - 네트워크  (0) 2025.09.13
Algorithm - BFS, DFS  (0) 2025.09.12
'C++ 프로그래머스 다이어리/BFS , DFS' 카테고리의 다른 글
  • 프로그래머스(C++) - 단어 변환
  • 프로그래머스(C++) - 게임 맵 최단거리
  • 프로그래머스(C++) - 네트워크
  • Algorithm - BFS, DFS
lucodev
lucodev
커피와 노트북 그리고 개발
  • lucodev
    루코 개발테이블
    lucodev
  • 전체
    오늘
    어제
    • 분류 전체보기 (171) N
      • Unreal5 프로젝트 다이어리 (73)
      • Unreal5 프로젝트 다이어리2 (11)
      • Unreal 팁 (8)
      • Unreal 디버깅 (8)
      • 코드 개인보관함 (8)
      • C++ 프로그래머스 다이어리 (49) N
        • Stack,Queue (6)
        • Hash (4)
        • Heap (2)
        • Sort (5)
        • Exhaustive search (5)
        • Greedy (2)
        • BFS , DFS (6)
        • Graph (2)
        • Dynamic Programming (1)
        • C++ Math (2)
        • 기타 문제 (13) N
      • 코딩테스트+@ (10) N
      • 알고리즘 스타디 (1)
      • 알고리즘 스타디 과제 (3)
  • 인기 글

  • 최근 글

  • 최근 댓글

  • 링크

  • 공지사항

  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 태그

    언리얼 로딩
    unreal 컷씬
    언리얼 foot step
    언리얼 look at
    unreal 시퀀스
    언리얼 behaviortree
    unreal 로딩
    언리얼 컷씬
    언리얼 비헤이비어트리
    언리얼 시퀀스
    언리얼
    언리얼 로딩창
    unreal look at
    언리얼 모션매칭
    언리얼 behavior tree
    unreal loading
    언리얼 페이드 아웃
    unreal sequence
    unreal 모션매칭
    언리얼 motionmatching
  • hELLO· Designed By정상우.v4.10.3
lucodev
프로그래머스(C++) - 타겟 넘버
상단으로

티스토리툴바