簡體   English   中英

找到多種生成數字的方法

[英]Find a Number of ways to Generate a Number

我只給出了Fibonacci digits only ,我必須找出僅使用K斐波那契數字生成數字的方法。

約束:

1<=K<=10
1<=N<=10^9

例如:

N=14 and K=3

有兩種方式:

(8,5,1) and (8,3,3) 

這是我的遞歸解決方案:

public static void num_gen(int i ,long val ,int used){

      if(used==0){

          if(val==n) ans++;
          return ;
      }

      if(i==Fib.length) return ;

      for(int j=0;j<=used;j++){

          long x = j*Fib[i];
          if(x+val<=n){
              num_gen(i+1,x+val, used-j);
          }
      }

}

對於較大的 N 值和 K=10,此解決方案將超時。 你能給我提供更復雜的算法嗎?

這可以表示為乘法多項式,其中指數是斐波那契數。

因子數為 K。

結果是指數等於 N 的結果多項式成員的系數。

示例:從 3 個數字組成數字 7 的方法數是多少,其中這 3 個數字中的每一個都可以是 1,2 或 3。

(x + x² + x³)³ = x⁹ + 3x⁸ +6x⁷ + 7x⁷ + 6x⁵ + 3x⁴ + x³

結果是 6,因為它是結果多項式的 x⁷ 成員的系數。

我想給你一個適用於另一種語言的解決方案,我希望能幫助你在將它翻譯成 Java 的過程中學習。 因為我不清楚如何以其他方式幫助您修復您正在處理的遞歸解決方案,因為我認為不需要遞歸。 也不需要預設的斐波那契數列。

這是在 Perl 中,它適用於:

$ perl fibber.pl 3 14
8,5,1
8,3,3
2 matches

但我不能保證它是完全正確的。

#!/usr/bin/perl
use bigint;
use List::Util qw(sum);

my ($digits, $goal) = @ARGV;
if (!($digits > 0) || !($goal > 0)) {
    die "Missing 2 arguments: the number count to sum, the value they sum to.";
}

sub fib {
    my ($a, $b) = @_;
    return sub {
        if (0 == scalar @_) {
            (my $r, $a, $b) = ($a, $b, $a+$b);
            return $r;
        } else {
            ($a, $b) = @_;
            (my $r, $a, $b) = ($b, $a+$b, $a+$b+$b);
            return $r;
        }
    }
}

my @f = (0) x $digits;
   @f = map {fib(1,2)} @f;
my @d = map {$_->()}   @f;
my $count = 0;
while ($d[0] < $goal) {
    if ($goal == sum @d) {
        $count++;
        print(join(",", @d)."\n");
    }
    my ($i, $a, $b) = (0, $d[$i], $f[$i]->());
    $d[$i] = $b;
    while ($goal <= $d[$i]) {
        $i++;
        if ($i == $digits) {
            print "$count matches\n";
            exit 0;
        }
        ($a, $b) = ($d[$i], $f[$i]->());
        $d[$i] = $b;
    }
    while ($i > 0) {
        $i--;
        $d[$i] = $f[$i]->($a, $b);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM