利用穷举法解决01背包问题

01背包动态规划算法可能有很多人不理解,贴出一个利用递归穷举法解决01背包问题的代码

package homework;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * Created by fushuang on 2016/8/15.
 */
public class bahe {
    public static int jishu=0;
    //如果用例为4    6 6 5 3 jishu输出的值为16哦~  最后func生成的结果却是只有12次,但是四组3个数的比一次,然后再每组的冠军有进行了一次比较
//代码思路,递归每次将一个人放入第一组,最后得出的结果为4 *3种结果,也就值最终返回fanc具体数值的个数,
//12个数分为四组  每三个和max比较
    //12 + 4 一共为16次
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        int count=scanner.nextInt();
        int sum=0;
        ArrayList list = new ArrayList<>();
        ArrayList firstlist = new ArrayList<>();
        for (int i = 0; i int a=scanner.nextInt();
            list.add(i,a);
            sum=sum+a;
        }
        System.out.println(list);
        sum=sum/2;
        count=count/2;

        System.out.println("第一队与平均值之间的差值:"+func(list, sum, count, firstlist));

        System.out.println("第一队的人为"+firstlist);
        list.removeAll(firstlist);
        System.out.println("第二队的人为"+ list);
        System.out.println(jishu);
    }

    public static int func(List list,int sum,int count,List firstlist){
        ArrayList finallist=new ArrayList<>();
        if (firstlist.size()==count){
           int first_sum=0;
            for (Integer a : firstlist) {
                first_sum=first_sum+a;
            }
            return Math.abs(first_sum-sum);
        }else {
            int min=Integer.MAX_VALUE;
            for (int i = 0; i < list.size(); i++) {
                ArrayList templist = new ArrayList<>(list);
                ArrayList ftemlist = new ArrayList<>(firstlist);
                ftemlist.add(templist.remove(i));

                int func = func(templist, sum, count, ftemlist);
                jishu++;
                if (funcreturn min;
        }

    }
}

你可能感兴趣的:(JAVA)