日期:2014-05-18  浏览次数:20673 次

关于那道趣的算法题:实现24点游戏求解的存储过程
我也写了一个,跟大家分享一下:)
--保存运算符之间的优先级,通过该表可以判断在一个表达式中加上一对括号是否会改变表达式的值。
create   table   t_operator   (operator1   char(1),operator2   char(1),flag   int)
insert   t_operator(operator1,operator2,flag)
select   '- ', '+ ', '2 '   union   all   select   '- ', '- ', '2 '   union   all   select   '/ ', '* ', '2 '   union   all  
select   '/ ', '/ ', '2 '   union   all   select   '* ', '+ ', '2 '   union   all   select   '* ', '- ', '2 '   union   all
select   '/ ', '+ ', '2 '   union   all   select   '/ ', '- ', '2 '   union   all   select   '+ ', '* ', '1 '   union   all
select   '+ ', '/ ', '1 '   union   all   select   '- ', '* ', '1 '   union   all   select   '- ', '/ ', '1 '
go

create   proc   p_calc_24   @a   int,@b   int,@c   int,@d   int
as
/*
    描述:
        给定任意四个整数,保持数字顺序不变,在数字中间加入+-*   /()等符号,使表达式等于24,括号最多加4-2=2对。    
    版本:
        时间                         修改人     操作
        2007年05月21日     mengmou   创建
    输入参数:
        任意四个整数.
    涉及:
        表t_operator,保存运算符之间的优先级,通过该表可以判断在一个表达式中加上一对括号是否会改变表达式的值。
    返回:
        所有满足条件的表达式的结果集。
    BUG:
        1.表达式[8+13-9*2]⑴派生出[(8+13-9)*2]⑵和[8+(13-9)*2]⑶,表达式⑶又派生出[(8+(13-9))*2]⑷,
            表达式⑷中的内层括号并不影响⑷的值,⑷相当于⑵的冗余,所以像⑷这类冗余不应该出现在结果集中。
            四个整数的表达式最多有两对括号,如果一一列举出所有情况并判断是否为冗余,会使代码会非常臃肿。
*/

set   nocount   on
set   arithabort   off  
set   arithignore   off  
set   ansi_warnings   off

declare   @operator_list   varchar(4),@x   int,@y   int,@z   int,@i   int,@sql   nvarchar(50),@result   numeric(38,6)
    ,@aa   varchar(10),@bb   varchar(10),@cc   varchar(10),@dd   varchar(10),@xx   char(1),@yy   char(1),@zz   char(1)
    ,@id   int,@operator   varchar(8000),@group_id   int,@new_operator   varchar(8000),@min_id   int,@max_id   int
    ,@old_group_id   int,@new_group_id   int
select   @aa   =   convert(varchar(10),@a)+ '.0 ',@bb   =   convert(varchar(10),@b)+ '.0 ',@cc   =   convert(varchar(10),@c)+ '.0 '
    ,@dd   =   convert(varchar(10),@d)+ '.0 ',@operator_list   =   '-+/* ',@x   =   1,@y   =   1,@z   =   1,@i   =   1,@new_operator   =   ' '
    ,@new_group_id   =   1,@old_group_id   =   0
declare   @t_expression   table(expression   varchar(50))
declare   @t_operator   table(group_id   int,id   int   identity,operator &