Java tutorial
//package com.java2s; import java.util.ArrayList; import java.util.List; public class Main { public static List<List<Integer>> getIndexSublist(int numbers, int length) { List<List<Integer>> sublists = new ArrayList<>(); if (length > numbers) { return null; //if length==numbers } else if (length == numbers) { ArrayList<Integer> temp = new ArrayList<Integer>(); for (int i = 0; i < numbers; i++) { temp.add(i); } sublists.add(temp); return sublists; //if length==1 } else if (length == 1) { for (int i = 0; i < numbers; i++) { ArrayList<Integer> temp = new ArrayList<Integer>(); temp.add(i); sublists.add(temp); } return sublists; } //for normal cases, initialize a list with one element for (int i = 0; i < numbers - length + 1; i++) { ArrayList<Integer> temp = new ArrayList<Integer>(); temp.add(i); sublists.add(temp); } //recursively add more elements try { getIndexSublist(numbers, length, sublists); } catch (IndexOutOfBoundsException e) { return new ArrayList<>(); } return sublists; } private static void getIndexSublist(int numbers, int length, List<List<Integer>> result) { List<List<Integer>> results = new ArrayList<>(); results.addAll(result); if (result.get(0).size() == length) { return; } result.clear(); for (List<Integer> one : results) { for (int i = 1; i < numbers; i++) { if (i > one.get(one.size() - 1)) { ArrayList<Integer> temp = new ArrayList<Integer>(); temp.addAll(one); temp.add(i); result.add(temp); } } } getIndexSublist(numbers, length, result); } }