帮我想个算法,有n个数(都是带2位小数的),这n个数将会分成2或3组,每一组的总和知道,求每组数都有哪些?
例如: 有6个数:1.5, 1.6, 2.1, 2.5, 3.2, 3.4 两组的和分别是:7.0, 7.3。这只是一个简单的,因为总的个数一般在10-20个左右。

解决方案 »

  1.   


    先把数据放到(动态)数组,然后回溯求第一组的可能组合。循环第一组的所有可能组,用同样的回溯求第2组跟第3组。
    回溯部分伪代码如下:
    arraylist a={1.5, 1.6, 2.1, 2.5, 3.2, 3.4 };
    decimal he=7.0
    aySol=new arraylist();
    aySolCollection=new arryalist();
    function GetSol(a[i],he){
        int iCount=a[i]
        for(i=0,i<a.length,i++){
           he-=a[i];
           if(0==he){
               aySolCollection.add(aySol);
           }else if(0<he){
               he+=a[i];
           }else{
               aySol.add(a[i]);
               GetSol(a.remove(a[i]),he)
               aySol.remove(a[i]);
               he+=a[i];
           }
       }
    }ps:我知道上面的代码可读性很差,但算法与可读性不可得兼, 凑合看吧。
    楼主实在看不懂就先看看回溯法入门教程,比如八皇后之类的问题。
      

  2.   

    检查了一下,改后:arraylist a={1.5, 1.6, 2.1, 2.5, 3.2, 3.4 }; 
    decimal he=7.0 
    aySol=new arraylist(); 
    aySolCollection=new arryalist(); 
    function GetSol(a[i],he){ 
        for(i=0,i <a.length,i++){ 
           he-=a[i]; 
           if(0==he){ 
               aySolCollection.add(aySol); 
           }else if(0 <he){ 
               aySol.add(a[i]); 
               GetSol(a.remove(a[i]),he) 
               aySol.remove(a[i]); 
               he+=a[i]; 
           } 
       } 
    } 其实核心代码才10几行.