Skip to content

Conversation

@gmlwjd9405
Copy link
Member

No description provided.

@gmlwjd9405
Copy link
Member Author

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

// https://www.baeldung.com/java-array-permutations
public static List<List> result = new ArrayList<>();

public static void main(String ... args){
    permute(new int[]{1, 2, 3});
    System.out.println(result);
}

public static List<List<Integer>> permute(int[] nums) {
    recursive(nums.length, nums);
    return result;
}

public static void recursive(int n, int[] nums) {
    if (n == 1) {
        result.add(toList(nums));
        return;
    }

    for (int i = 0; i < n - 1; i++) {
        recursive(n - 1, nums);
        if (n % 2 == 0) { // 짝수
            swap(nums, i, n - 1);
        } else { // 홀수
            swap(nums, 0, n - 1);
        }
    }
    recursive(n - 1, nums);
}

public static void swap(int[] input, int a, int b) {
    int tmp = input[a];
    input[a] = input[b];
    input[b] = tmp;
}

public static List<Integer> toList(int[] input) {
    List<Integer> list = new ArrayList<>();
    for (int num : input) {
        list.add(num);
    }
    return list;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants