Dev/Algorithm

[프로그래머스] 삼총사 - Java

VIPeveloper 2024. 5. 29. 13:45
728x90
반응형

문제

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

 

생각

  • DFS 를 까먹어서,, 이번엔 삼중포문으로 풀었다.

코드

public class Main {
    public static void main(String[] args) {
        System.out.println(solution(new int[]{-2, 3, 0, 2, -5}));   // 2
        System.out.println(solution(new int[]{-3, -2, -1, 0, 1, 2, 3}));    // 5
        System.out.println(solution(new int[]{-1, 1, -1, 1})); // 0
    }
    public static int solution(int[] number) {
        int answer = 0;
        for (int i = 0; i < number.length; i++) {
            for (int j = i; j < number.length; j++) {
                for (int k = j; k < number.length; k++) {
                    if(i==j || j == k || i == k) continue;
                    if(number[i]+number[j]+number[k] == 0){
                        answer++;
                    }
                }
            }
        }
        return answer;
    }
}

다른 사람 풀이

public class Main {
    public static void main(String[] args) {
        System.out.println(solution(new int[]{-2, 3, 0, 2, -5}));   // 2
        System.out.println(solution(new int[]{-3, -2, -1, 0, 1, 2, 3}));    // 5
        System.out.println(solution(new int[]{-1, 1, -1, 1})); // 0
    }
    public static int solution(int[] number) {
        answer = 0;
        nums=new int[number.length];
        for(int i=0;i<number.length;i++){
            nums[i]=number[i];
        }
        dfs(0,0,0);
        return answer;
    }
    public static int answer;
    public static int[] nums;
    public static void dfs(int index, int sum, int count){
        if(count==3 && sum==0){
            answer++;
        }else if(index<nums.length){
            dfs(index+1,sum+nums[index],count+1);
            dfs(index+1,sum,count);
        }
    }
}
728x90
반응형