Created
November 13, 2013 22:15
-
-
Save ylegall/7457442 to your computer and use it in GitHub Desktop.
Find the k permutations of n items.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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