Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Comparator;
- import java.util.List;
- import java.util.Scanner;
- public class Main {
- public static void main(String[] args) {
- Scanner in = new Scanner(System.in);
- int n = in.nextInt();
- ArrayList<Integer> a = new ArrayList<>();
- while (in.hasNextInt()) {
- a.add(in.nextInt());
- }
- a.sort(Comparator.naturalOrder());
- powerSet(new ArrayList<>(), a,0, n)
- .forEach(l -> {
- l.forEach(e -> {
- System.out.print(e);
- System.out.print(" ");
- });
- System.out.println();
- });
- }
- private static List<List<Integer>> powerSet(List<Integer> cur, List<Integer> set, int max, int sum) {
- List<List<Integer>> res = new ArrayList<>();
- if (cur.stream().mapToInt(Integer::intValue).sum() == sum) {
- res.add(cur);
- return res;
- }
- for (int i = max; i < set.size(); ++i) {
- List<Integer> next = new ArrayList<>(cur);
- next.add(set.get(i));
- if (next.stream().mapToInt(Integer::intValue).sum() <= sum) {
- res.addAll(powerSet(next, set, i, sum));
- }
- }
- return res;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement