[leetcode] Medium-46번. Permutations 문제풀이

반응형
728x90
반응형

문제

https://leetcode.com/problems/permutations/

 

Permutations - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 

 

 

풀이코드

package SITE03_leetcode.medium;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * https://leetcode.com/problems/permutations/
 */
public class M018_leetcode46_Permutations {
    List<List<Integer>> resultList = new ArrayList<List<Integer>>();
    List<Integer> paramList = new ArrayList<>();
    int[] map;
    int n;
    boolean[] visited;

    public static void main(String[] args) {
        M018_leetcode46_Permutations solution = new M018_leetcode46_Permutations();

        //int[] dx = {1,2,3};
        int[] dx = {0,1};

        System.out.println(solution.permute(dx));
    }

    public List<List<Integer>> permute(int[] nums) {
        this.map = nums;
        n = nums.length;

        visited = new boolean[n];

        dfs(paramList);

        return resultList;
    }

    public void dfs(List<Integer> paramList) {
        // 탈출 조건
        if (paramList.size() == n) {
            resultList.add(new ArrayList<>(paramList));
            return;
        }

        // 구현
        for (int i = 0; i < n; i++) {
            if (!visited[i]) {
                visited[i] = true;
                paramList.add(map[i]);


                dfs(paramList);

                visited[i] = false;
                paramList.remove(paramList.size() - 1);
            }
        }
    }
}

 

 

반응형

Designed by JB FACTORY