[动态规划] leetcode 338 Counting Bits

problem:https://leetcode.com/problems/counting-bits

        爬台阶类型。我的做法是num拆分为比它小的最大2^n的值加上另一个数,然后这两个的dp叠加。

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> dp(num + 1);
        dp[0] = 0;
        int cur = 1;
        int next = 1;
        int idx = 0;
        for(int i = 1;i <= num;i++)
        {
            if(i == next)
            {
                dp[i] = 1;
                idx++;
                cur = next;
                next = pow(2, idx);
            }
            else
            {
                dp[i] = dp[i - cur] + 1;
            }
            
        }
        return dp;
    }
};

 

posted @ 2019-08-10 17:31  fish1996  阅读(154)  评论(0编辑  收藏  举报