zoukankan      html  css  js  c++  java
  • 非递归解决组合问题

    //非递归搜索回溯框架
    dep:=1;//搜索起点,深度为1
    repeat
        while g[dep]<=搜索方案数 do//能进则进
        begin
            inc(g[dep]);//取前进方案
            if 不符条件 then continue;
            if dep=步数或达到终点条件 then print
            else inc(dep);        
        end;
       
        g[dep]:=0;

      dec(dep);//回溯,恢复状态
    until dep=0;//回溯到起点之前时结束搜索

    begin
        readln(n,r);
        dep:=1;//搜索起点,深度为1
        repeat        
            while g[dep]<=n do//能进则进
            begin
                b[g[dep]]:=0;//回溯
                repeat
                    inc(g[dep]);    
                until b[g[dep]]=0;//取前进方案
                if (g[dep]>n)  then break;//不符条件
                b[g[dep]]:=1;//记录之间结果
                if dep=r then print //终点
                else inc(dep);        //进
            end;            
            b[g[dep]]:=0;//回溯
            g[dep]:=0;
            dec(dep);    
        until dep=0;//回溯到起点之前时结束搜索
        writeln(s);
    end.

    var n,i,t,m:integer;
        g:array[0..100]of integer;
        b:set of 0..100;
    begin
     readln(n,m);
     t:=1;
     b:=[];
     fillchar(g,sizeof(g),0);
     repeat
      while t<=n do
      begin
       b:=b-[g[t]];
       repeat
        inc(g[t]);
       until (not(g[t] in b)) and ((g[t]>g[t-1]));//过滤条件
       if (g[t]>n) then break;
       b:=b+[g[t]];
       if t=m then
       begin
        for i:=1 to m do write(g[i],' ');
        writeln;
       end
       else inc(t);
       end;
       b:=b-[g[t]];
       g[t]:=0;
       dec(t);
      until t=0;
    end.

  • 相关阅读:
    POJ 3680_Intervals
    POJ 3680_Intervals
    POJ 3686_The Windy's
    POJ 3686_The Windy's
    Codeforces 629C Famil Door and Brackets
    Codeforces 629D Babaei and Birthday Cake(树状数组优化dp)
    Codeforces 629D Babaei and Birthday Cake(线段树优化dp)
    Codeforces 628F Bear and Fair Set
    18.04.26 魔兽世界终极版
    18.4.20 STL专项练习8选6
  • 原文地址:https://www.cnblogs.com/nbalive2001/p/3333191.html
Copyright © 2011-2022 走看看