leetcode Solving Thought Analysis of 50-56 Questions

  1. Pow(x, n)
    Implement pow(x, n), which is the N-power function of X.

The simplest is direct concatenation

class Solution {
public:
    double myPow(double x, int n) {
        long long N = n;
        if (N < 0) {
            x = 1 / x;
            N = -N;
        }
        double ans = 1;
        for (long long i = 0; i < N; i++)
            ans = ans * x;
        return ans;
    }
};

For exponent 2n, we can decompose it into two n multiplied, which saves a lot of time, but requires additional space to store the intermediate amount, which can be obtained by dividing and dividing recursion.

class Solution {
public:
    double fastPow(double x, long long n) {
        if (n == 0) {
            return 1.0;
        }
        double half = fastPow(x, n / 2);
        if (n % 2 == 0) {
            return half * half;
        } else {
            return half * half * x;
        }
    }
    double myPow(double x, int n) {
        long long N = n;
        if (N < 0) {
            x = 1 / x;
            N = -N;
        }
        return fastPow(x, N);
    }
};

class Solution {
public:
    double myPow(double x, int n) {
        long long N = n;
        if (N < 0) {
            x = 1 / x;
            N = -N;
        }
        double ans = 1;
        double current_product = x;
        for (long long i = N; i ; i /= 2) {
            if ((i % 2) == 1) {
                ans = ans * current_product;
            }
            current_product = current_product * current_product;
        }
        return ans;
    }
};

  1. N-queens problem
    The question of n Queens is how to place n Queens on an n x n board and prevent them from attacking each other.
    Given an integer n, returns the solution to all the different N Queens problems.
    Each solution contains a clear chess placement scheme for the n-queen problem in which''Q'and'.' represent the queen and the empty space, respectively.

This type of thinking that needs to be considered step by step and then goes back one step at a time is typically backtracking.

class Solution {
public:
    void solve(vector<vector<string>>& res, vector<string>& tmp, vector<bool>& cols_, vector<bool>& diag1s_, vector<bool>& diag2s_, int n, int row){
        if(row == n){
            res.push_back(tmp);
            return;
        }
        for(auto col = 0; col < n; col++){
            int ll = row + col;
            int rr = row - col + n - 1;
            if (cols_[col] && diag1s_[ll] && diag2s_[rr]){
                tmp[row][col] = 'Q';
                cols_[col] = false;
                diag1s_[ll] = false;
                diag2s_[rr] = false;

                solve(res, tmp, cols_, diag1s_, diag2s_, n, row+1);

                tmp[row][col] = '.';
                cols_[col] = true;
                diag1s_[ll] = true;
                diag2s_[rr] = true;
            }
        }
    }
    
    vector<vector<string>> solveNQueens(int n) {
        vector<vector<string>> res;
        vector<string> tmp(n, string(n, '.'));
        vector<bool> cols_(n, true);
        vector<bool> diag1s_(2*n-1, true);
        vector<bool> diag2s_(2*n-1, true);
        solve(res, tmp, cols_, diag1s_, diag2s_, n, 0);
        return res;
    }
    
};

  1. Queen N II
    Given an integer n, returns the number of different solutions for Queen n.

This topic is similar to the previous one, except that you don't need to output all types, but just give the number of solutions.

class Solution {
public:
    int totalNQueens(int n) {
        int res = 0;
        vector<bool> cols_(n, true);
        vector<bool> diag1s_(2 * n - 1, true);
        vector<bool> diag2s_(2 * n - 1, true);
        solve(&res, cols_, diag1s_, diag2s_, n, 0);
        return res;        
    }

    void solve(int *res, vector<bool>& cols_, 
            vector<bool>& diag1s_, vector<bool>& diag2s_, int n, int row)
    {
        if(row == n)
        {
            (*res)++;
            return;
        }
        for(auto col = 0; col < n; col++)
        {
            int ll = row + col;
            int rr = row - col + n - 1;
            if (cols_[col] && diag1s_[ll] && diag2s_[rr])
            {
                
                cols_[col] = false;
                diag1s_[ll] = false;
                diag2s_[rr] = false;

                solve(res, cols_, diag1s_, diag2s_, n, row+1);

                cols_[col] = true;
                diag1s_[ll] = true;
                diag2s_[rr] = true;
            }
        }
    }
   
};
  1. Maximum Subordinate Sum
    Given an integer array nums, find a continuous subarray with the largest sum (the subarray contains at least one element) and return its maximum sum.

This topic is easy to solve by greedy method

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int n = nums.size();
        int currSum = nums[0], maxSum = nums[0];

        for(int i = 1; i < n; ++i) 
        {
            currSum = max(nums[i], currSum + nums[i]);
            maxSum = max(maxSum, currSum);
        }
        return maxSum;      
    }
};
  1. Spiral Matrix
    Given a matrix containing m x n elements (m rows, n columns), return all the elements in the matrix in a clockwise spiral order.

This topic can be achieved by direct visual thinking

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        if (matrix.size() == 0)
            return {};

        int coloum = matrix[0].size(), line = matrix.size();
        vector<int> ret;

        int begin = 0, end = coloum, top = 0, bottom = line;
        while (true)
        {
            for (int i = begin; i < end; i++)
            {
                ret.push_back(matrix[top][i]);
            }
            top++;
            if (top >= bottom) break;

            for (int i = top; i < bottom; i++)
            {
                ret.push_back(matrix[i][end - 1]);
            }
            end--;
            if (end <= begin) break;

            for (int i = end - 1; i >= begin; i--)
            {
                ret.push_back(matrix[bottom - 1][i]);
            }
            bottom--;
            if (top >= bottom) break;            

            for (int i = bottom - 1; i >= top; i--)
            {
                ret.push_back(matrix[i][begin]);
            }
            begin++;
            if (end <= begin) break;           
        }

        return ret;
    }
};
  1. Jump Game
    Given a non-negative integer array, you are initially in the first position of the array.
    Each element in the array represents the maximum length you can jump at that location.
    Determine if you can reach the last location.

The idea of this topic is: the maximum position that a location can reach, the node on the left side of it must be able to reach

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int k = 0;
        for (int i = 0; i < nums.size(); i++)
        {
            if (i > k) return false;
            k = max(k, i + nums[i]);
            if (k >= nums.size()) return true;
        }
        return true;
    }
};
  1. Consolidation interval
    Given a set of intervals, merge all overlapping intervals.

There are two ways to think about this topic: the first is to sort the intervals first, and then make judgments one by one; the second is to map all the intervals to "segments" and then output "segments".

class Solution {
public:
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        vector<vector<int>> res;
        if(intervals.empty()) return res;

        auto cmp = [](vector<int> &a, vector<int> &b) {return a[0] < b[0];};
        sort(intervals.begin(), intervals.end(), cmp);

        res.emplace_back(intervals[0]);
        for(int i = 1; i < intervals.size(); i++) {
            int bk = res.size() - 1;
            if(res[bk][1] >= intervals[i][0]) {
                if(res[bk][1] < intervals[i][1]) {
                    res[bk][1] = intervals[i][1];
                } 
            } else {
                res.emplace_back(intervals[i]);
            }
        }

        return res; 
    }
};


97 original articles were published. 14 were praised. 30,000 visits+
Private letter follow

Posted by HeinekenBeer on Fri, 31 Jan 2020 20:05:02 -0800