Java examples for Data Structure:Algorithm
permutations With First Element
//package com.java2s; import java.util.ArrayList; import java.util.List; public class Main { public static <T> List<List<T>> permutationsWithFirstElement( List<T> listings) throws Exception { List<T> list = new ArrayList<T>(listings); list.remove(0);/*from w w w . j av a 2s .co m*/ List<List<T>> perms = permutations(list); for (List<T> l : perms) { l.add(listings.get(0)); } list = new ArrayList<T>(); list.add(listings.get(0)); perms.add(list); return perms; } public static <T> List<List<T>> permutations(List<T> listings) throws Exception { /* * String debug = "["; for (int i = 0; i < listings.size(); ++i) { debug * += listings.get(i).toString(); if (i < (listings.size() - 1)) { debug * += ", "; } } debug += "]"; System.out.println("permutations(" + debug * + ")"); */ List<List<T>> perms = new ArrayList<List<T>>(); if (listings.size() == 0) { // System.out.println("permutations return list of size 0"); return perms; } List<T> list = new ArrayList<T>(); list.add(listings.get(0)); perms.add(list); if (listings.size() == 1) { // System.out.println("permutations return list of size " + // perms.size()); return perms; } List<List<T>> perms2 = permutations(listings.subList(1, listings.size())); perms.addAll(perms2); for (List<T> l : perms2) { List<T> newList = new ArrayList<T>(l); newList.add(listings.get(0)); perms.add(newList); } // System.out.println("permutations return list of size " + // perms.size()); return perms; } }