- to do
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);
- 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;
- nth was 0, xor 1 gets1;
- nth was 1, xor 0, gets1
- cleared if x is 0 =>: original number, get nth;
- if was 0, xor 0 gets 0;
2)if was 1, xor 1 gets 1
恍惚记得第一次被提起的那次
那时觉得dp是个不明觉厉的玩意
晚上刷机半天 还没成功。。。欸啥么嘛