fork(4) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. List<List<Integer>> sodaPacks(int[] packs, int n, int index) {
  11. List<List<Integer>> result = new ArrayList<>();
  12.  
  13. // Base case: we have one way to make an empty list
  14. if (n == 0) {
  15. result.add(new ArrayList<>());
  16. return result;
  17. }
  18.  
  19. // Recursive step: we solve a smaller problem
  20. for (int i = index; i < packs.length; i++) {
  21. if (n - packs[i] >= 0) {
  22. List<List<Integer>> ways = sodaPacks(packs, n - packs[i], i);
  23. for (List<Integer> way : ways) {
  24. // Tack on our solution:
  25. way.add(packs[i]);
  26. result.add(way);
  27. }
  28. }
  29. }
  30. return result;
  31. }
  32.  
  33. public static void main (String[] args) throws java.lang.Exception
  34. {
  35. Scanner sc = new Scanner(System.in);
  36. int n = sc.nextInt();
  37. int[] a = new int[n];
  38. for (int i = 0; i < n; i++) {
  39. a[i] = sc.nextInt();
  40. }
  41. int sodas = sc.nextInt();
  42. Ideone solution = new Ideone();
  43. System.out.println(solution.sodaPacks(a, sodas, 0));
  44. sc.close();
  45. }
  46. }
Success #stdin #stdout 0.15s 321344KB
stdin
4
1 2 3 5
5
stdout
[[1, 1, 1, 1, 1], [2, 1, 1, 1], [3, 1, 1], [2, 2, 1], [3, 2], [5]]