프로그래머스(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
  • 전체
    오늘
    어제
    • 분류 전체보기 (218) N
      • Unreal 프로젝트 다이어리 (115) N
        • 첫번째 프로젝트 (73)
        • 두번째 프로젝트 (42) N
      • Unreal 팁 (8)
      • Unreal 디버깅 (8)
      • C++ 프로그래머스 (52)
        • Stack,Queue (7)
        • Hash (4)
        • Heap (2)
        • Sort (5)
        • Exhaustive search (5)
        • Greedy (2)
        • BFS , DFS (7)
        • Graph (2)
        • Dynamic Programming (1)
        • C++ Math (2)
        • 기타 문제 (14)
      • C++ 백준 (4)
      • C++ 팁 (1)
      • 개인 코테 & 스타디 <비공개> (29)
        • 코드 개인보관함 (9)
        • 코딩테스트+@ (11)
        • 알고리즘 스타디 (6)
        • 알고리즘 스타디 과제 (3)
        • 비공개 (0)
  • 인기 글

  • 최근 글

  • 최근 댓글

  • 링크

  • 공지사항

  • 블로그 메뉴

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

    unreal inventory
    언리얼 상호작용
    언리얼
    언리얼 시퀀스
    언리얼 컷씬
    언리얼 behaviortree
    언리얼 npc
    unreal npc
    언리얼 parkour
    언리얼 behavior tree
    언리얼 퀘스트시스템
    언리얼 프로그래스바
    언리얼 ui
    언리얼 인벤토리
    unreal 시퀀스
    언리얼 비헤이비어트리
    unreal 파쿠르
    unreal 인벤토리
    언리얼 파쿠르
    unreal
  • hELLO· Designed By정상우.v4.10.3
lucodev
프로그래머스(C++) - 타겟 넘버
상단으로

티스토리툴바