递归深度首先搜索Integer ArrayList Java

时间:2015-06-23 04:35:09

标签: java recursion arraylist set depth-first-search

我要做的主要是查看一组数字,找到这些数字的所有子集并最终打印出来。我完全坚持编写递归方法。我们的想法是使用布尔arraylist作为树的一种形式,并遍历它测试我正在寻找的所有不同的总和。问题是它甚至没有正确地通过树,所以任何建议都会有很大的帮助。

package programmingassignment3;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class SubsetSum {

    public ArrayList<Integer> set1 = new ArrayList<Integer>(Arrays.asList(1,2,3,4));
    int d = 6;

    public void  test(){
        Collections.sort(set1);
        for(int i =0;i<set1.size();i++)
            if(set1.get(i)>d)
                set1.remove(i);
        ArrayList<Boolean> set1test = new ArrayList();
        recSubSetSum(set1test); 
    }


    public void recSubSetSum(ArrayList<Boolean> subsetList)
    {

        if(sumOfList(subsetList)>=d)
            System.out.println("Output Set(WIP)");
        ArrayList<Boolean> leftList = new ArrayList();
        ArrayList<Boolean> rightList = new ArrayList();
        for(int i =0;i<set1.size();i++)
        {
            leftList = new ArrayList(subsetList);
            rightList = new ArrayList(subsetList);
            if(set1.size()>leftList.size())
                leftList.add(true);
            if(set1.size()>rightList.size())
                rightList.add(false);

            if(sumOfList(leftList)<d)
            {
                recSubSetSum(leftList);
                if(set1.size()>rightList.size())
                    rightList.add(false);
            }
            if(sumOfList(rightList)<d)
                recSubSetSum(rightList);
        }
    }

    public int sumOfList(ArrayList<Boolean> subSetList)
    {
        int sum = 0;

        for(int i = 0;i<subSetList.size();i++)
        {

            if(subSetList.get(i))
                sum+=set1.get(i);
        }
        return sum;
    }
}

0 个答案:

没有答案