[CareerCup][Google Interview] 打印所有的Binary Number

If the Fibonacci series is 1,2,3,5,8,13,….. then 10 can be written as 8 + 2 ==> 10010 and 17 can be written as 13 + 3 + 1 ==> 100101. Got it?? The Question was, given n, I need to get all possible representations of n in Fibonacci Binary Number System. as 10 = 8 + 2 ==> 10010 also 10 = 5 + 3 + 2 ==> 1110

这里8+2= 10,

1 2 3 5 8 13

0 1 0 0 1 -->二进制数为10010

DP来解决,复杂度O(n * n * m), m是给的数,n是小于m的fib数的个数。

sum[i][k]表示用前i个数(第i个数一定会用到),和为k的情况总数。

最后sum[i][m],  0 < i < n,的和就是总的组合数

 1 #include <iostream>
 2 using namespace std;
 3 
 4 int main()
 5 {
 6     int f[10];
 7 
 8     f[0] = 1;
 9     f[1] = 2;
10 
11     for(int i = 2; i < 10; i++)
12         f[i] = f[i-1] + f[i-2];
13 
14     int sum[10][100];
15 
16     int size = 0;
17 
18     int N = 13;
19 
20     while(size < 10)
21     {
22         if (f[size] <= N)
23             size++;
24         else
25             break;
26     }
27 
28     memset(sum, 0, sizeof(sum));
29 
30     for(int i = 0; i < size; i++)
31     {
32         sum[i][f[i]] = 1;
33         for(int j = 0; j < i; j++)
34             for(int k = 1; k <= N - f[i]; k++)
35                 sum[i][k + f[i]] += sum[j][k];
36     }
37 
38     int ret = 0;
39     for(int i = 0; i < size; i++)
40         ret += sum[i][N];
41 
42     cout << ret << endl;
43 }
posted @ 2012-11-01 23:16  chkkch  阅读(430)  评论(0编辑  收藏  举报