Created
October 1, 2012 10:26
-
-
Save Higgcz/3810770 to your computer and use it in GitHub Desktop.
Given a specified total t and a list of integers, find all distinct sums using numbers from the list that add up to t. Use findSum(t, given_numbers, new LinkedList<Integer>())
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static LinkedList<LinkedList<Integer>> findSum(int t, LinkedList<Integer> input, LinkedList<Integer> used) { | |
LinkedList<LinkedList<Integer>> inner, out = new LinkedList<LinkedList<Integer>>(); | |
Integer sum = 0, temp; | |
LinkedList<Integer> usedBk, inputBk = (LinkedList<Integer>) input.clone(); | |
while ( !inputBk.isEmpty() ) { | |
temp = inputBk.poll(); | |
if ( temp == sum ) { | |
continue; | |
} | |
sum = temp; | |
usedBk = new LinkedList<Integer>(used); | |
usedBk.add(sum); | |
if ( sum.intValue() == t ) { | |
out.add(usedBk); | |
} else if ( sum > t ) { | |
continue; | |
} else if ( sum < t ) { | |
inner = findSum(t - sum, inputBk, usedBk); | |
if ( inner != null ) { | |
out.addAll(inner); | |
} | |
} | |
} | |
return out; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment