Skip to content

Instantly share code, notes, and snippets.

@Coac
Last active February 14, 2016 19:06
Show Gist options
  • Save Coac/96b2cbcb12dbd0ab7286 to your computer and use it in GitHub Desktop.
Save Coac/96b2cbcb12dbd0ab7286 to your computer and use it in GitHub Desktop.
NumberSumDecomposition with duplication
public class Application {
public static void main(String[] args) {
int[] tab = new int[4];
tab[0] = 1;
tab[1] = 10;
tab[2] = 2;
tab[3] = 5;
getSumDecomposition(53, tab);
}
static void getSumDecompositionRec(int target, int sum, int candidates[],
int sumNumbersIndex[], int sumNumbersIndexSize) {
if (sum > target)
return;
if (sum == target) {
System.out.print("[");
for (int i = 1; i <= sumNumbersIndexSize; i++) {
System.out.print(candidates[sumNumbersIndex[i]]);
if (i == sumNumbersIndexSize) {
System.out.print("]");
} else {
System.out.print(",");
}
}
System.out.println("");
}
for (int i = sumNumbersIndex[sumNumbersIndexSize]; i < candidates.length; i++) {
sumNumbersIndex[sumNumbersIndexSize + 1] = i;
getSumDecompositionRec(target, sum + candidates[i], candidates,
sumNumbersIndex, sumNumbersIndexSize + 1);
}
}
static void getSumDecomposition(int target, int candidates[]) {
System.out.println("--- BEGIN ---");
long time = System.nanoTime();
int[] sumNumbersIndex = new int[100000];
sumNumbersIndex[0] = 0;
getSumDecompositionRec(target, 0, candidates, sumNumbersIndex, 0);
time = (System.nanoTime() - time) / 1000000;
System.out.println("--- END in " + time + " ms ---");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment