回溯法--算法框架(2)

回溯法--算法框架(2)
基本框架和组成部分:

public abstract class Problem {
     //判断是否有解向量
     boolean flag ;
     //解向量
      Comparable [] x;
     //解向量的大小
     int n;
     //判断是否为完整解
     public abstract boolean complete( int k);
     //打印解向量
     public abstract void printSolution( int k);
     //判断是否为局部的合适解
     public abstract boolean isPartial( int k);
     //回溯探索
     public abstract void explore( int k);
}


由于某些组合问题的解向量 x的分量取值是不固定的,所以需要用 makeItem来创建
import java. util.Vector ;

public abstract class CombineProblem extends Problem {
     //创建解向量的第 k个分量的取值集合
     public abstract Vector <Comparable> makeItem( int k);
     //如果是完整解,打印完整解,依次將 x[k]赋其可能值,如果合适,便立下一个 k,反之,回溯
     @Override
     public void explore ( int k) {
           //判断是否为完成解
           if ( complete(k )) {
               flag = true ;
               //是完整解,打印
              printSolution (k);
           }
           //退出
           if ( k >= n) {
               return;
           }
           //vector是可变长数组
           Vector <Comparable> items = makeItem (k);
           for ( Comparable comparable : items ) {
               x [k] = comparable;
               //如果是合适的部分解,遍历下一个 k
               if ( isPartial(k )) {
                   explore (k + 1 );
              }
          }
     }
}


  




posted @ 2015-05-26 18:24  外禅内定,程序人生  阅读(158)  评论(0编辑  收藏  举报