有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

通过回溯算法实现Java power set

我似乎对使用回溯实现幂集算法有疑问。我想要实现的是非常简单的,生成任意给定数字的幂集: 例[1 2 3]=>;[1] [2] [3] ; [1,2] [1,3] [2,3] ; [1,2,3]

我的算法是使用一个堆栈来放置数字,它将数字添加到堆栈中并发送给计算人员。代码如下:

public int calculatePowerSet(int x, LinkedList<Integer> arr)
{
    int size = 1;
    int nrOfTimes=0;
    int calculate =0;
    boolean goOn=true;
    Stack<Integer> stack = new Stack<Integer>();
    int k=0, len = arr.size();
    double temp=0.0f;
    while(size<=len)
    {
        goOn=true;
        stack.push(arr.get(0));
        k = arr.indexOf(stack.peek());
        temp = size;    //ignore these as they are for calculating time
        temp/=len;      //ignore these as they are for calculating time
        temp*=100;      //ignore these as they are for calculating time
        setPowerSetPrecentage((int)temp);
        while(goOn)
        {
            if(isStopProcess())return 0;
            if((k==len)&&(stack.size()==0)) goOn=false;
            else if(stack.size()==size) 
            {
                String sign = "";   
                if((stack.size()%2)==0) sign="+";
                else sign="-";
                calculate =calculateSets(stack.toArray(), sign, calculate, x);
                k = arr.indexOf(stack.pop())+1;
            }
            else if(k==len)
                k = arr.indexOf(stack.pop())+1;
            else
            {
                prepereStack(stack,arr.get(k));
                k++;
            }
        }
        size++;
    }
    return calculate;
}

以下是计算方法:

private int calculate(int[] arr2, int x)
{
        int calc=1;

        float rez = 0;
        for(int i=0;i<arr2.length;i++)
            calc*=arr2[i];
        rez = (float)(x/calc);
        calc = (int) (rez+0.5d);
        return calc;
}

该代码似乎对20以下的所有数字都非常有效,但在那之后,我似乎得到了错误的结果。我无法手动检查这些数字,因为有数百种组合。例如,对于25个数字的一个输入,我应该得到1229的结果,而不是1249。我不确定我遗漏了什么,因为我认为算法在理论上应该是可行的,所以如果有人有任何建议,那就太好了


共 (1) 个答案

  1. # 1 楼答案

    我建议将发电机组的发电量从计算中分离出来。虽然发电机组有一些非常有效的算法,但我建议在需要效率之前,保持算法的简单性

    private void forEachSet(List<Integer> currentSet, List<Integer> rest) {
        if (rest.isEmpty()) {
            process(currentSet);
        } else {
            Integer nextInt = rest.remove(0);
            forEachSet(currentSet, rest);
            currentSet.add(nextInt);
            forEachSet(currentSet, rest);
            current.remove(nextInt);
            rest.add(nextInt);
        }
    }
    
    public forEachSet(List<Integer> set) {
        forEachSet(new ArrayList<>(), new ArrayList<>(set));
    }