6.10 climbingStairs & greyCode

  • to do

1] Climbing Stairs

    int climbStairs(int n) {
        if (n<1) return 0;
        else if (n<4) return n;

        int dp[n+1] = {0};//the nth val stands for number of possible ways given n
        dp[1] = 1;
        dp[2] = 2;
        for (int i=3; i<n+1; ++i) {
            dp[i] = dp[i-1] + dp[i-2];
        }
        return dp[n];
    }

2] Gray Code 下次快刷

    void flipNthBit(int& target, int k) {
        target ^= (1<<k); //xor kth bit
    }

    vector<int> grayCode(int n) {
        if (n==0) return {0};

        vector<int> ret;
        int retSize = pow(2,n);

        bool used[retSize];
        fill(used, used+retSize, false);

        int num=0, tmp = num;
        for (int i=0; i<n;) {
            if (used[tmp]==false) {
                num = tmp;
                used[num]=true;
                ret.push_back(num);
                if (ret.size()==retSize) break;
                i = 0;
            } else {
                tmp = num;
                ++i;
            }
            flipNthBit(tmp, i);
        }
        return ret;
    }

note 1: array op

using the syntax that you used:

int array[100] = {-1};

>says "set the first element to -1 and the rest to 0 since all omitted elements are set to 0.
In C++, to set them all to -1, you can use something like 
``` c++
 std::fill(iter begin, inter end, value_to_set)

or

std::fill_n(array, 100, -1);

node2: bit op

Setting a bit

number |= 1 << x; //OR

Clearing a bit

number &= ~(1 << x); //111101111, AND

Toggling a bit

number ^= 1 << x; // XOR

Checking a bit

bit = (number >> x) & 1;

====Changing the nth bit to x ====

number ^= (-x ^ number)  & (1 << n);
  1. Bit n will be set if x is 1 : -x=all1s, XOR to get flipped num, AND to get nth now flipped bit; rest XOR with 0 stays the same;
  1. nth was 0, xor 1 gets1;
  2. nth was 1, xor 0, gets1
  1. cleared if x is 0 =>: original number, get nth;
  1. if was 0, xor 0 gets 0;
    2)if was 1, xor 1 gets 1

恍惚记得第一次被提起的那次
那时觉得dp是个不明觉厉的玩意

晚上刷机半天 还没成功。。。欸啥么嘛

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容