Here's some code that finds all the possible selections without relying on storing the previously generated selection and checking if you have already output them:
public static void permuteArray(int[] array, int start) {
if (array.length == start) {
System.out.println(Arrays.toString(array));
} else {
for (int i = start; i < array.length; i++) {
int temp = array[i];
array[i] = array[start];
array[start] = temp;
permuteArray(array, start + 1);
temp = array[i];
array[i] = array[start];
array[start] = temp;
}
}
}
public static void makeCombinations(int[] array, int startElement, int minValue, int maxValue, int length, boolean permute)
{
// iterate through all values from minValue to maxValue minus the remaining spaces
int remainingSpacesAfterThisOne = (length - 1) - startElement;
for(int i = minValue; i <= (maxValue - remainingSpacesAfterThisOne); i++)
{
array[startElement] = i;
if(startElement < (length - 1))
makeCombinations(array, startElement + 1, i + 1, maxValue, length, permute);
else
{
if(permute)
// print out all permutations of this array:
permuteArray(array, 0);
else
// print out the combination
System.out.println(Arrays.toString(array));
}
}
}
public static void makeCombinations(int max, int length, boolean permute)
{
int[] array = new int[length];
makeCombinations(array, 0, 1, max, length, permute);
}
public static void main (String[] args)
{
makeCombinations(10, 5, true);
}
The code generates all possible selections of length non-repeating numbers where the numbers in the selection are in ascending order, and optionally finds all the possible permutations of those selections.
If you have a max value of 10 and a length of 5, and your selection is in ascending order, then for the first item you can only choose a number from 1 to 6 inclusive (or else you won't have enough numbers to fill out the rest of the selection without repeating one or going out of ascending order). So the algorithm iterates over the possible legal values for the first item, then for each value recursively generates the possible selections that can make up the remainder of the list, enforcing ascending order by passing in the first value plus one as the min value.
Once there are no more values to generate, recursion stops and then the ascending-order selection can be permuted using a simple recursive permutation function to find all possible orderings.