leetcode 397. Integer Replacement 二分查找

来源:互联网 发布:java反射获取方法私有 编辑:程序博客网 时间:2024/06/02 04:41

Given a positive integer n and you can do operations as follow:

If n is even, replace n with n/2.
If n is odd, you can replace n with either n + 1 or n - 1.
What is the minimum number of replacements needed for n to become 1?

Example 1:

Input:
8

Output:
3

Explanation:
8 -> 4 -> 2 -> 1
Example 2:

Input:
7

Output:
4

Explanation:
7 -> 8 -> 4 -> 2 -> 1
or
7 -> 6 -> 3 -> 2 -> 1

题意很简单,就是做一个简单的DFS深度优先遍历查找,

注意要使用long long数据类型,使用int可能超时

代码如下:

#include <iostream>#include <vector>#include <map>#include <set>#include <queue>#include <stack>#include <string>#include <climits>#include <algorithm>#include <sstream>using namespace std;class Solution {public:    int integerReplacement(int n)     {        if (n <= 1)            return 0;        else            return (int)getRes(n);    }    int getRes(long long n)    {        if (n == 1)            return 0;        else        {            if (n % 2 == 0)                return getRes(n / 2) + 1;            else            {                int a = getRes(n - 1) + 1;                int b = getRes(n + 1) + 1;                return min(a, b);            }        }    }};
原创粉丝点击