Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
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
Tags more
Archives
Today
Total
관리 메뉴

공부블로그

[프로그래머스] 폰켓몬 본문

IT/알고리즘

[프로그래머스] 폰켓몬

So1_b 2022. 8. 15. 20:25

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

 

프로그래머스

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

programmers.co.kr

성공한 코드

import java.util.*;

class Solution {
    public int solution(int[] nums) {
        HashSet<Integer> set = new HashSet<Integer>();
        
        //중복 제거
        for(int n: nums)
            set.add(n);
        
        int n = nums.length/2;
        
        if(set.size() >= n)
            return n;
        else 
            return set.size();
    }
}

 

반복문과 재귀는 상호호환이 가능하다고 배워 재귀로도 구현해보았으나 실패

시도 1)

import java.util.HashSet;

class Solution { 
    int n;   //고를 수 있는 포켓몬 수 
    int max = 1; //종류 최댓값
    int[] arr; //nums
    
    StringBuilder sb = new StringBuilder(6 * 5000);  // 6자리 * 5000
    HashSet<String> set = new HashSet<String>();     // 중복 제거용 set
    
    void pokesmon(int idx, int lv){
        
        if(lv>=n) { // 포켓몬을 다 고를 경우
            
            // 중복된 포켓몬 제거
            for(String s: sb.toString().split("")){
                set.add(s);
            }
            // 포켓몬 종류의 개수 확인 
            int size = set.size();
            if(size > max)
                max = size;
            set.clear(); 
            
            return;
        }else {
            int t = arr.length - (n-lv); 
            for(int i = idx; i <= t; i++){
                sb.append(arr[i]);
                pokesmon(i+1, lv++);
                sb.deleteCharAt(sb.length()-1);
            }
        }
    }
    public int solution(int[] nums) {
        arr = nums; //배열 연결
        n   = nums.length/2; // 선택할 수 있는 포켓몬 개수 
        
        pokesmon(0 , 0);
        
        return max;
    }
}

테스트 케이스는 통과했지만 실행시 테스트 1, 7 ~ 20번이 메모리 초과

오버헤드(매개변수전달) 등으로 메모리가 부족한것같기도 함.

이유는 정확하게 모름.

'IT > 알고리즘' 카테고리의 다른 글

[백준] 9093번 단어 뒤집기  (0) 2022.08.22
[프로그래머스] 체육복  (0) 2022.08.18
단순 삽입 정렬  (0) 2022.08.08
순열 알고리즘  (0) 2022.07.29
멱집합 알고리즘  (0) 2022.07.26
Comments