A financial department found that the total amount was incorrect when closing. It is likely that one or more of them have been omitted from the details. If the detailed account list is known, can you find out which one or several missed accounts by programming?
If there are multiple possibilities, output all possible situations.
We stipulate that the first line entered by the user is the total amount with error.
Next is an integer n representing the number of sub ledger entries to be entered below.
Next is the n-line integer, which represents the amount of each account.
Require program output: all combinations of amounts that may be missed. 1 line per case. Amounts are arranged from small to large, separated by spaces.
For example:
User input:
6
5
3
2
4
3
1
Note: the total amount of errors is 6; there are 5 details in total.
At this point, the program should output:
1 3 3
1 2 4
3 4
For convenience, it may be assumed that all amounts are integers; each amount does not exceed 1000, and the number of details of the amount does not exceed 100.
package com.liu.ex2; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class Main { public static ArrayList<Integer> list = new ArrayList<Integer>(); public static ArrayList<String> result = new ArrayList<String>(); public static int[] value; //Statement of detailed accounts public static int sum = 0; //Indicates the normal total amount - total amount in error value public int getSum() { int result = 0; for(int i = 0;i < list.size();i++) result += list.get(i); return result; } public void dfs(int step) { while(step < value.length) { list.add(value[step]); if(getSum() == sum) { ArrayList<Integer> tempList = new ArrayList<Integer>(); for(int i = 0;i < list.size();i++) tempList.add(list.get(i)); Collections.sort(tempList); StringBuilder s = new StringBuilder(""); for(int i = 0;i < tempList.size();i++) s.append(tempList.get(i)+" "); if(!result.contains(s.toString())) { result.add(s.toString()); System.out.println(s); } } step++; dfs(step); list.remove(list.size() - 1); } } public static void main(String[] args) { Main test = new Main(); Scanner in = new Scanner(System.in); int w = in.nextInt(); int n = in.nextInt(); value = new int[n]; for(int i = 0;i < n;i++) { int a = in.nextInt(); value[i] = a; sum = sum + a; } sum = sum - w; test.dfs(0); } }