Skip to content

Instantly share code, notes, and snippets.

@developer-sdk
Last active September 1, 2016 13:15
Show Gist options
  • Save developer-sdk/a8db20ec7d070873d3a6072570e2bb7f to your computer and use it in GitHub Desktop.
Save developer-sdk/a8db20ec7d070873d3a6072570e2bb7f to your computer and use it in GitHub Desktop.
public class Permutation {
public static void main(String[] args) {
int[] arr = { 1, 2, 3 };
perm(arr, 0);
}
public static void perm(int[] arr, int pivot) {
if (pivot == arr.length) {
print(arr);
return;
}
for (int i = pivot; i < arr.length; i++) {
swap(arr, i, pivot);
perm(arr, pivot + 1);
swap(arr, i, pivot);
}
}
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void print(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i == arr.length - 1)
System.out.println(arr[i]);
else
System.out.print(arr[i] + ",");
}
}
}
public class PermutationString {
public static void main(String[] args) {
permutation("abcd");
}
public static void permutation(String str) {
permutation("", str);
}
private static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0)
System.out.println(prefix);
else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment