language agnostic - Algorithm to calculate combinations without duplicates -
i have following problem:
calculate combination of 3 digits number consisting of 0-9, , no duplicate allowed.
as far know, combinations don't care ordering, 123
equal 312
, number of possible combinations should
( 10 ) = 120 combinations ( 3 )
that said: know how calculate permutations (via backtracking) don't know how calculate combinations.
any hint?
finding comnbination done via backtracking. @ each step - "guess" if should or should not add current candidate element, , recurse on decision. (and repeat both "include" , "exclude" decisions).
here jave code:
public static int getcombinations(int[] arr, int maxsize) { return getcombinations(arr, maxsize, 0, new stack<integer>()); } private static int getcombinations(int[] arr, int maxsize, int i, stack<integer> currentsol) { if (maxsize == 0) { system.out.println(currentsol); return 1; } if (i >= arr.length) return 0; //"guess" include: currentsol.add(arr[i]); int x = getcombinations(arr, maxsize-1, i+1, currentsol); //clean up: currentsol.pop(); x += getcombinations(arr, maxsize, i+1, currentsol); return x; }
you can run following demo:
public static void main(string args[]) { int[] data = {0,1,2,3,4,5,6,7,8,9}; int x = getcombinations(data, 3); system.out.println("number of combinations generated: " + x); }
and series of combinations, , @ number of combinations printed (unsurprisingly, 120)
Comments
Post a Comment