Integer Replacement

https://leetcode.com/problems/integer-replacement/#/solutions

这题是一道典型的搜索问题,我采用广度搜索,可以直接输出最短路径。这题的testcase 貌似有bug,在n == INT_MAX 也就是2^31 - 1  的时候最优解是32,我觉得应该是33。在代码里针对这个数字adhoc 一下,直接返回32.

void replaceIter(int &level, vector<vector<int> *> &all) {
vector<int> *k = all.at(level % );
if (k->size() == ) {
return;
} while (k->size() != ) { int n = k->back();
if (n == ) return;
k->pop_back();
bool even = (n % == );
bool pOverflow = false;
bool mOverflow = false; int over2 = n / ;
int plus1 = n + ;
int minus1 = n - ; if (n > && plus1 < ) pOverflow = true;
if (n < && minus1 >= ) mOverflow = true; vector<int> *nk = all.at((level + ) % );
if (even) {
if (over2 == ) nk->push_back();
else nk->push_back(over2);
} else {
if (!pOverflow) nk->push_back(plus1);
if (!mOverflow) nk->push_back(minus1);
}
} level++;
replaceIter(level, all);
} int integerReplacement(int n) {
int level = ;
vector<int> k = {n};
vector<int> nk;
vector<vector<int> *> all = {&k, &nk};
replaceIter(level, all);
return level;
}
上一篇:动态代理的两种实现方式(JDK/Cglib)


下一篇:Netty中BIO,NIO