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 | 31 |
Tags
- 리액트의 작동방식
- Lifting State Up
- 프로그래머스#JAVA
- Kruskal Algorithm
- DB Navigator
- java
- 리액트 상태값 업데이트
- useReducer
- Segment Tree
- 객체지향 설계 5원칙
- DFS
- batch udpate
- MST구현
- JS Array Functions
- useState
- 섬 연결하기
- BOJ2042
- State
- react
- state update scheduling
- useContext
- React 훅 사용규칙
- codility
- heap
- Modern Javascript
- 프로그래머스
- Greedy
- spread operator
- rest operator
- 리액트 성능 최적화
Archives
- Today
- Total
개발하는SM
[프로그래머스] 타겟 넘버 본문
programmers.co.kr/learn/courses/30/lessons/43165
코딩테스트 연습 - 타겟 넘버
n개의 음이 아닌 정수가 있습니다. 이 수를 적절히 더하거나 빼서 타겟 넘버를 만들려고 합니다. 예를 들어 [1, 1, 1, 1, 1]로 숫자 3을 만들려면 다음 다섯 방법을 쓸 수 있습니다. -1+1+1+1+1 = 3 +1-1+1+1+
programmers.co.kr
문제 설명
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 이하인 자연수입니다.
풀이
배열 A를 순차적으로 돌면서, 각 값들에 대해 2가지 경우의 수가 존재함(더하거나, 빼거나).
배열 내부에 있는 값들의 개수 n에 따라, 경우의 수가 2의 n승 개 만큼 존재한다.
주어지는 숫자의 개수는 20개 이하이므로(2^20 = 1,048,576 ), DFS를 활용해 해결해도 시간복잡도 상의 문제는 없음.
import java.util.*;
class Solution {
public static int answer = 0;
public void dfs(int curSum, int depth, int[] nums, int target){
if(depth == nums.length){
if(target == curSum) answer += 1;
return;
}
// 더하거나, 빼거나 둘 중 하나임.
dfs(curSum + nums[depth], depth + 1, nums, target);
dfs(curSum - nums[depth], depth + 1, nums, target);
return;
}
public int solution(int[] numbers, int target) {
dfs(0, 0, numbers, target);
return answer;
}
}'Algorithm > DFS, BFS' 카테고리의 다른 글
| [프로그래머스] 여행 경로(DFS 풀이) (0) | 2021.02.17 |
|---|---|
| [프로그래머스] 단어 변환 (0) | 2021.02.17 |
| [프로그래머스] 네트워크 (0) | 2021.02.16 |