Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.List;
- public final class Problem
- {
- static class IntList
- {
- IntList (int i, IntList next) {
- this.i = i;
- this.next = next;
- }
- public int i;
- public IntList next;
- }
- // works best if set sorted in increasing order
- static void solutions (int target, int... set)
- {
- IntList remaining = null;
- for (int i: set)
- remaining = new IntList(i, remaining);
- List<IntList> solutions = solutions(target, 0, null, remaining);
- int i = 1;
- for (IntList solution: solutions) {
- System.out.print("solution " + i + ": ");
- while (solution != null) {
- System.out.print(solution.i);
- if (solution.next != null) System.out.print(", ");
- solution = solution.next;
- }
- System.out.println();
- ++i;
- }
- }
- static List<IntList> solutions (int target, int total, IntList selected, IntList remaining)
- {
- if (remaining == null)
- return Collections.emptyList();
- List<IntList> solutions = new ArrayList<>();
- int total2 = total + remaining.i;
- if (total2 == target)
- // first item yield a solution
- solutions.add(new IntList(remaining.i, selected));
- else if (total2 < target)
- // include first item
- solutions.addAll(
- solutions(target, total2, new IntList(remaining.i, selected), remaining.next));
- // omit first item
- solutions.addAll(solutions(target, total, selected, remaining.next));
- return solutions;
- }
- public static void main (String[] args)
- {
- solutions(7, 1, 2, 3, 4);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement