Get all sub list of a given list
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class AllSubList {
/**
* 1.get all subsets of {2,3} as A
* 2.all subsets of {2,3} adds 1 as B
* 3.A+B = all subsets of {1,2,3}
* @param args
*/
public static void main(String[] args) {
System.out.println(subsets(Arrays.asList(1,2,3)));
}
static List<List<Integer>> subsets(List<Integer> list){
if(list.isEmpty()){
List<List<Integer>> ans = new ArrayList<>();
ans.add(Collections.emptyList());
return ans;
}
Integer first = list.get(0);
List<Integer> rest = list.subList(1,list.size());
List<List<Integer>> subans = subsets(rest);
List<List<Integer>> subans2 = insertAll(first,subans);
return concat(subans,subans2);
}
//referential transparency
private static List<List<Integer>> concat(List<List<Integer>> subans, List<List<Integer>> subans2) {
List<List<Integer>> r = new ArrayList<>(subans);
r.addAll(subans2);
return r;
}
//referential transparency
private static List<List<Integer>> insertAll(Integer first, List<List<Integer>> subans) {
List<List<Integer>> result = new ArrayList<>();
for(List<Integer> list:subans){
List<Integer> copyList = new ArrayList<>();
copyList.add(first);
copyList.addAll(list);
result.add(copyList);
}
return result;
}
}