Skip to content

Instantly share code, notes, and snippets.

@ylegall
Created November 13, 2013 22:15
Show Gist options
  • Save ylegall/7457442 to your computer and use it in GitHub Desktop.
Save ylegall/7457442 to your computer and use it in GitHub Desktop.
Find the k permutations of n items.
import java.io.*;
import java.util.*;
public class Kperm {
static void kperm(List<Integer> items, int k) {
kperm(items, new ArrayList<Integer>(), k);
}
static void kperm(List<Integer> items, List<Integer> accum, int k) {
if (accum.size() == k) {
System.out.println(accum);
return;
}
for (int i = 0; i < items.size(); ++i) {
int item = items.get(i);
List<Integer> newItems = new ArrayList<>();
newItems.addAll(items.subList(0,i));
newItems.addAll(items.subList(i+1,items.size()));
accum.add(item);
kperm(newItems, accum, k);
accum.remove(accum.size()-1);
}
}
public static void main(String[] args) {
kperm(Arrays.asList(1,2,3,4,5), 3);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment