java实现漏掉的账目明细

某财务部门结账时发现总金额不对头。很可能是从明细上漏掉了某1笔或几笔。如果已知明细账目清单,能通过编程找到漏掉的是哪1笔或几笔吗?
如果有多种可能,则输出所有可能的情况。
我们规定:用户输入的第一行是:有错的总金额。
接下来是一个整数n,表示下面将要输入的明细账目的条数。
再接下来是n行整数,分别表示每笔账目的金额。
要求程序输出:所有可能漏掉的金额组合。每个情况1行。金额按照从小到大排列,中间用空格分开。
比如:

用户输入:
6
5
3
2
4
3
1
表明:有错的总金额是6;明细共有5笔。
此时,程序应该输出:
1 3 3
1 2 4
3 4

为了方便,不妨假设所有的金额都是整数;每笔金额不超过1000,金额的明细条数不超过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;    //表示明细账目清单
    public static int sum = 0;    //表示正常总金额-出错总金额值
    
    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);
    }
}
原文地址:https://www.cnblogs.com/a1439775520/p/13078216.html