Sunday, December 3, 2017

Print all permutations of elements of an array

Print all permutations of elements of an array: Keeping first element at first position and arranging rest of the elements all possible ways. Similarly for second , third and so on. This problem can be solved in recursive way. First 0th to Nth element, then 1st to Nth then 2nd to Nth and so on.
Here is the diagram to understand this recursive approach and then sample java code.:


public class Permutations {

/**
* @param args
*            the command line arguments
*/
void printArray(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");

}
System.out.println("");
}

void permute(int[] a, int k) {
if (k == a.length)
printArray(a);
else
/*
* There will be mainly a.length (size of array) recursion path. For example if
* array is {1,2,3} then there will be three recursion path as
* permute({1,2,3},0), permute({2,1,3},0) & permute({3,1,2},0) in accordance
* with first loop
*/
for (int i = k; i < a.length; i++) {
// Swap when i>k
int temp = a[k];
a[k] = a[i];
a[i] = temp;
permute(a, k + 1);
/*
* This swap is restore the array as same as the beginning of current recursion
* path. So that while backtracking next swap should happen w.r.t. original
* state.
*/
temp = a[k];
a[k] = a[i];
a[i] = temp;
}
}

public static void main(String[] args) {
Permutations p = new Permutations();
int a[] = { 1, 2, 3 };
p.permute(a, 0);
}

}

Permutations II

Given a collection of numbers that might contain duplicates, return all possible unique permutations.
Example:
Input: [1,1,2]
Output:
[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]
public List> permuteUnique(int[] nums) {
List> ans = new ArrayList>();
if (nums == null || nums.length == 0) {
return ans;
}
permute(ans, nums, 0);
return ans;
}

private void permute(List> ans, int[] nums, int index) {
if (index == nums.length) {
List temp = new ArrayList<>();
for (int num : nums) {
temp.add(num);
}
ans.add(temp);
return;
}
Set appeared = new HashSet<>();
for (int i = index; i < nums.length; ++i) {
if (appeared.add(nums[i])) {
swap(nums, index, i);
permute(ans, nums, index + 1);
swap(nums, index, i);
}
}
}

private void swap(int[] nums, int i, int j) {
int save = nums[i];
nums[i] = nums[j];
nums[j] = save;
}

No comments:

Post a Comment