Here is a sample solution, using backtracking. It will generate you all possible permutations of size K and store them in lists
field.
List<List<Integer>> lists = new ArrayList<List<Integer>>();
void permutate(int[] arr, int k) {
internalPermutate(arr, k, 0, 0);
}
void internalPermutate(int[] arr, int k, int step, int index) {
if (step == k) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < k; i++) {
list.add(arr[i]);
}
lists.add(list);
}
for (int i = step + index; i < arr.length; i++) {
swap(arr, step, i);
internalPermutate(arr, k, step + 1, i);
swap(arr, step, i);
}
}
private void swap(int[] arr, int x, int y) {
int temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
public static void main(String[] args) {
new SomeClass().permutate(new int[] { 1, 2, 3, 4 }, 2);
System.out.println(lists);
}
This solution doesn't deal with situation when we have the same elements in array, but you can just exclude them before permutation.