Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

java - Find a Number of ways to Generate a Number

I have given Fibonacci digits only , i have to find out the numbers of ways to generate a number using K Fibonacci numbers only.

Constraints:

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

For Example:

N=14 and K=3

There are two ways:

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

Here is my recursive solution:

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);
          }
      }

}

This solution will timeout for large value of N and K=10. Can you provide me algorithm with better complexity.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This can be expressed as multiplying polynomials where exponents are Fibonacci numbers.

Number of factors is K.

The result is a coefficient of the member of the result polynomial whose exponent equals N.

Example: What is the number of ways to compose number 7 from 3 numbers where each of these 3 numbers can be 1,2 or 3.

(x + x2 + x3)3 = x? + 3x? +6x? + 7x? + 6x? + 3x? + x3

Result is 6 since it is the coefficient of the x? member of the result polynomial.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...