求一算法,10个自然数之和为90,不要变态的穷举算法,要能运行的有结果的。谢谢~~

解决方案 »

  1.   

    我做过类似的题目,现在把我的算法给你把:
    program coutSums;{$APPTYPE CONSOLE}uses
      SysUtils,
      Classes,
      System;var
      count:integer;
      numbers:array [1..20] of Integer;
      numCount,maxSum:integer;
      signs:array of Boolean;
      vsum:Integer;  inputS:String;
      i:integer;
    procedure countAllSum(var sum:integer;posN:integer);
    var
      tsum:integer;
    begin
      if posN<>numCount then
      begin
        tsum:=sum;
        sum:=sum+numbers[posN];
        signs[sum]:=True;
        countAllSum(sum,posN+1);
        sum:=tsum;
        countAllSum(sum,posN+1);
      end
      else
      begin
        sum:=sum+numbers[posN];
        signs[sum]:=True;
      end;
    end;procedure ReadNumArrays(theNums:string);
    var
      ipos,icount:integer;
      istr:string;
    begin
      iPos:=2;
      while ipos<Length(theNums)-1 do
      begin
        icount:=0;
        while (theNums[ipos+icount]<>',') and (theNums[ipos+icount]<>'}') do
        begin
          Inc(icount);
        end;
        iStr:=Copy(theNums,ipos,icount);
        inc(numCount);
        numbers[numCount]:=StrToInt(iStr);
        maxSum:=maxSum+numbers[numCount];
        ipos:=ipos+icount+1;
      end;
    end;begin
      { TODO -oUser -cConsole Main : Insert code here }
       maxSum:=0;
       numCount:=0;
       vsum:=0;
       count:=0;   writeln('Input the number{1,2,3,4};');
       Readln(inputS);
       ReadNumArrays(inputS);   SetLength(signs,maxSum+1);
       
       for i:=1 to maxSum do
       begin
         signs[i]:=False;
       end;   countAllSum(vsum,1);   for i:=1 to maxSum do
       begin
         if signs[i] then
           Inc(count);
       end;   
       writeln(count);
       Read(inputS);
    end.