카테고리 없음

[프로그래머스 | Java Lv.3] N으로 표현 (DP, 동적 프로그래밍)

Trudy | 송연 2024. 5. 21. 20:49

문제

https://school.programmers.co.kr/learn/courses/30/lessons/42895

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


접근

 

어떻게 접근해야할 지 감이 안와서 밑에 링크 걸어둔 블로그를 보고 방법을 참고해서 풀기 시작했다. 

5가 1개면 만들 수 있는 숫자는 5 하나 (5)

5가 2개면, 5+5, 5-5, 5*5, 5/5, 55 (10, 0, 25, 1, 55) 

5가 3개면, 5+(5+5), 5-(5+5), 5*(5+5), 5/(5+5),

(5+5)-5, (5+5)/5,

 

5+(5-5), 5-(5-5), 5*(5-5), 5/(5-5),

(5-5)-5, (5-5)/5, 

... 

555

 

문제1 -  ConcurrentModificationException

HashSet)을 순회하면서 동시에 수정하려고 할 때 발생합니다. 현재 코드에서 tmpset 컬렉션을 참조하고 있고, tmp를 순회하는 동안 set을 수정하기 때문에 이 예외가 발생합니다.

public class Ex1 {
    static HashSet<Integer> set =  new HashSet<Integer>();

    public static boolean cal(int N, int number, int length){
        HashSet<Integer> tmp = new HashSet<>();
        tmp = set;

		...

        }

        return false;
    }

    public static int solution(int N, int number) {

        set.add(N);

        for (int i = 2; i <= 8; i++) {
            if(cal(N, number, i)) return i;
        }

        return -1;
    }

    public static void main(String[] args) {
        System.out.println(solution(5, 12));
        System.out.println(solution(2, 11));
    }
}

 

다음과 같이 수정해서 해결

public static boolean cal(int N, int number, int length) {
        HashSet<Integer> tmp = new HashSet<>(set);
        ..
        
 }

 


첫번째 제출 - 실패

 

https://school.programmers.co.kr/questions/14645

그러네.. 규범님 감사합니다..

그래서 풀이를 봤을 때 List 안에 Set으로 각 회차마다의 조합들을 저장한 것이구나


최종 코드

 

 

 


 

참고

https://small-stap.tistory.com/65

 

[프로그래머스] N으로 표현 Java 풀이

이 글은 혼자 학습한 내용을 바탕으로 작성되었습니다. 틀리거나 잘못된 정보가 있을 수 있습니다. 댓글로 알려주시면 수정하도록 하겠습니다. 1. 문제 아래와 같이 5와 사칙연산만으로 12를 표

small-stap.tistory.com