题意:遇到偶数除以2,奇数 +1 或者 - 1。看多少次后能达到1。
思路:BFS。
class Solution {
public:
int integerReplacement(int n) {
pair<int64_t, int64_t> addNode;
addNode.first = n, addNode.second = 0;
node.push_back(addNode);
int i = 0;
while(node[i].first != 1) {
if(node[i].first % 2 == 0) {
addNode.first = node[i].first / 2;
addNode.second = node[i].second + 1;
node.push_back(addNode);
}
else {
addNode.first = node[i].first + 1;
addNode.second = node[i].second + 1;
node.push_back(addNode);
addNode.first = node[i].first - 1;
addNode.second = node[i].second + 1;
node.push_back(addNode);
}
i ++;
}
return node[i].second;
}
private:
vector<pair<int64_t, int64_t>> node;
};
另一种思路是尽可能减少1的位数。比如111-> 1000 好于 111->110。但是也有例外,如3,要单独讨论。
class Solution {
public:
int integerReplacement(int n) {
int c = 0;
int64_t m = n;
while(m != 1) {
if((m & 1) == 0) m >>= 1;
else if(m == 3 || ((m >> 1) & 1) == 0) m --;
else m ++;
c ++;
}
return c;
}
};