[LeetCode#46] Permutation

2024. 8. 21. 16:00·Algorithm/문제풀이

❒ Description


제목 Permutation
링크 https://leetcode.com/problems/permutations/description/
자료구조 비선형 (그래프)
시간복잡도 O(n!)


Permutation(순열)이란, 모든 가능한 경우를 그래프 형태로 나열한 결과라고 할 수 있다.

이 문제는 BackTraking을 통해서 해결하는 문제인데, 모든 가능한 순열을 생성하기 때문에

nums의 크기가 커질수록 시간이 급격히 증가한다.

 

❒ Solution


1. Solution1

public class Solution {

    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> results = new ArrayList<>();
        List<Integer> elements = Arrays.stream(nums).boxed().toList();
        dfs(results, new ArrayList<>(), elements);
        return results;
    }

    private void dfs(List<List<Integer>> results, List<Integer> prevElement, List<Integer> elements) {
        if (elements.isEmpty()) {
            results.add(prevElement.stream().toList());
        }

        for (Integer e : elements) {
            List<Integer> nextElements = new ArrayList<>(elements);
            nextElements.remove(e);

            prevElement.add(e);
            dfs(results, prevElement, nextElements);
            prevElement.remove(e);
        }
    }
}

 

 

2. Solution2

public class V2 {
    
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    boolean[] visited;
    public List<List<Integer>> permute(int[] nums) {
        visited = new boolean[nums.length];
        backtrack(nums);
        return res;
    }

    private void backtrack(int[] nums) {
        if (path.size() == nums.length) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (visited[i]) continue;
            path.add(nums[i]);
            visited[i] = true;
            backtrack(nums);
            visited[i] = false;
            path.removeLast();
        }
    }
}

처음에 방문여부를 생각했었는데 구현은 못했었다.

Solution2가 코드를 이해하는데 더 쉬운 것 같다.

 

 

 

 


'Algorithm > 문제풀이' 카테고리의 다른 글

[LeetCode#787] Cheapest Flights Within K Stops  (0) 2024.09.10
[LeetCode#207] Course Schedule  (0) 2024.08.30
[프로그래머스#42576] 완주하지 못한 선수  (0) 2024.08.16
[LeetCode#973] K Closest Points to Origin  (0) 2024.08.08
[LeetCode#23] Merge K sorted Lists  (0) 2024.08.06
'Algorithm/문제풀이' 카테고리의 다른 글
  • [LeetCode#787] Cheapest Flights Within K Stops
  • [LeetCode#207] Course Schedule
  • [프로그래머스#42576] 완주하지 못한 선수
  • [LeetCode#973] K Closest Points to Origin
gilbert9172
gilbert9172
gilbert9172 님의 블로그 입니다.
  • gilbert9172
    バックエンド
    gilbert9172
  • 전체
    오늘
    어제
    • All Categories (207)
      • 우테코 7기 (21)
        • 1주차 (8)
        • 2주차 (5)
        • 3주차 (6)
      • Langauge (6)
        • Java (3)
        • Kotlin (3)
      • Back-End (13)
        • SpringBoot (1)
        • Trouble Shooting (0)
        • Setup & Configuration (1)
        • SQL (3)
        • Redis (8)
      • Architecture (6)
        • Multi Module (1)
        • DDD (5)
      • CS (30)
        • Data Structure (6)
        • Operating System (0)
        • Network (12)
        • Database (10)
        • Design Pattern (2)
      • Algorithm (78)
        • 내용 정리 (18)
        • 문제풀이 (60)
      • DevOps (6)
        • AWS (5)
        • Git (1)
      • Front-End (1)
        • Trouble Shooting (1)
      • Project (6)
        • 페이스콕 (6)
      • Book (39)
        • 친절한 SQL 튜닝 (9)
        • 데이터 중심 애플리케이션 설계 (14)
        • 이벤트 기반 마이크로서비스 구축 (6)
        • Spring Batch docs (10)
        • Quartz docs (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    Two-Pointer
    greedy
    부분단조성
    binarysearch
    Back-Tracking
    sliding-window
    오블완
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.2
gilbert9172
[LeetCode#46] Permutation
상단으로

티스토리툴바