Leetcode 600. Non-negative Integers without Consecutive Ones

来源:互联网 发布:北师大网络教育学费 编辑:程序博客网 时间:2024/05/21 13:55

题目:Given a positive integer n, find the number of non-negative integers less than or equal to n, whose binary representations do NOT contain consecutive ones。

思路:对于每个数的二进制表示,假设这个数有n位。令f(n) 表示从右到左第n位的满足要求的数量,所给数为num。当num[n] 位时,如果为0;则f(n)=f(n-1);如果为1,把1变小为0,所得数都是比原来小,而且从第num[n-1]位开始也和原问题一样了,当还为1时,就必须令num[n-1]等于0,因为不能包含consecutive ones,从第num[n-2]开始也可以归结到原问题上;也就是f(n)=f(n-1)+f(n-2)。假设num=1000100,分为1000000和100两段,也就是遇见10时,当遇见11时,只能改第二个为0,所以return f(n-1)就行了。状态方程写出来,但是最后的返回条件一直没理清。看了别人的才顺好了。附别人最简洁的代码:

class Solution {public:   int findIntegers(int num) {    static int fb[31] = { 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946,        17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578 };    if (num < 3) return num + 1;    for (int bt = 29; bt >= 0; --bt) // bt should start from 30, but OJ accepts it from 29.        if (num & (1 << bt)) return num & (1 << (bt - 1)) ? fb[bt] : fb[bt - 1] + findIntegers((num & ~(1 << bt)));}};


阅读全文
0 0