─━ IT ━─

[릿코드, Leetcode] [JAVA] Permutations

DKel 2021. 4. 3. 08:57
반응형
 

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

Leetcode - Permutations

설명

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

Example:

Input: nums = [1,2,3]

Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

제한사항

 

  • 1 <= nums.length <= 6
  • -10 <= nums[i] <= 10
  • All the integers of nums are unique.

 

 

소스코드

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

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> answer = new ArrayList<List<Integer>>();
        
        int depth = 0;
        permutation(nums, depth, answer);
        
        return answer;
    }
    
    private void permutation(int[] nums, int depth, List<List<Integer>> answer) {
        if(depth == nums.length - 1) {
            List<Integer> temp = new ArrayList<>();
            for(int item : nums) {
                temp.add(item);
            }
            answer.add(temp);
            return;
        }
        for(int i=depth; i<nums.length; i++) {
            swap(nums, depth, i);
            permutation(nums, depth + 1, answer);
            swap(nums, depth, i);
        }
    }
    
    private void swap(int[] nums, int depth, int i) {
        int temp = nums[depth];
        nums[depth] = nums[i];
        nums[i] = temp;
    }
}

제출한 소스코드

 

lemondkel - Overview

4-Year Web programmer. lemondkel has 41 repositories available. Follow their code on GitHub.

github.com

 

반응형