2015-02-10 63 views
0

我似乎有一个关于使用回溯实现功率集算法的问题。我想要实现的是相当简单的,生成任何给定数字的功率集: Ex。 [1 2 3] => [1] [2] [3]; [1,2] [1,3] [2,3]; [1,2,3]通过回溯算法设置Java功能

我的算法使用堆栈来放置数字,它将数字添加到堆栈并发送它们进行计算。代码如下:

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

“对于25个数字的一​​个输入,我应该得到1229的结果”? 25个不同项目的功率设置的大小是“2^25”,即>> 1229.谨慎解释? – alfasin 2015-02-10 04:04:19

+0

是的,数字本身是从我在功率设定结束后执行的计算中得出的...例如,每个数字的组合将被数字x除。然而,问题仍然是功率集的产生。 – 2015-02-10 04:07:16

+0

因此总而言之,你的计算*将*不正确,因为你无法正确生成功率设置?你有什么证据证明1229是正确的,而不是1249? – 2015-02-10 04:15:56

回答

0

我会建议从你的计算中分离出发电机组的代。虽然有一些非常有效的发电机组算法,但我建议保持它非常简单,直到您需要提高效率。

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)); 
} 
+0

虽然解决方案是一个很好的解决方案,但由于我正在使用大量数据,因此我将在套件内出现问题。如果我尝试在这种性质中实现某些东西,那么我将得到堆错误,因为它在内存中的空间不足。这就是为什么我选择与Stacks合作并尽可能保持简单。 – 2015-02-12 15:01:40

+0

@DanutNiculae我不确定我是否理解你的评论。我的解决方案没有集合内的集合:它只是维护两个列表:当前的和其余的。关于列表,没有什么比堆栈更低效。真正的主要区别是我的解决方案使用递归来维护状态。 – sprinter 2015-02-12 20:13:50