Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/hee q16234 #148

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open

Feature/hee q16234 #148

wants to merge 2 commits into from

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.

1 participant