LeetCode Algorithm 0051 - 0055

返回总目录

LeetCode Algorithm 0051 - 0055



0051 - N-Queens (Hard)

Problem Link: https://leetcode.com/problems/n-queens/

Description

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

8-queens

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens’ placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

Example:

Input: 4
Output: [
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/n-queens/

namespace P51NQueens
{
    class Solution
    {
        private:
        const char dot = '.';
        const char queen = 'Q';

        public:
        vector<vector<string>> solveNQueens(int n)
        {
            vector<vector<string>> results;
            vector<string> result = vector<string>(n, string(n, dot));
            Solving(results, n, result, 0);
            return results;
        }

        private:
        void Solving(vector<vector<string>>& results, int n, vector<string>& result, int row)
        {
            if (row == n)
            {
                results.push_back(result);
                return;
            }

            for (int col = 0; col < n; col++)
            {
                result[row][col] = queen;

                bool flag = true;

                for (int r = 0; r < row; r++)
                {
                    // 同列
                    if (result[r][col] == queen)
                    {
                        flag = false;
                        break;
                    }

                    int diff = row - r;
                    int left = col - diff;
                    int right = col + diff;

                    // 左上方斜线
                    if (left >= 0 && result[r][left] == queen)
                    {
                        flag = false;
                        break;
                    }

                    // 右上方斜线
                    if (right < n && result[r][right] == queen)
                    {
                        flag = false;
                        break;
                    }
                }

                if (flag)
                {
                    Solving(results, n, result, row + 1);
                }

                result[row][col] = dot;
            }
        }
    };
}

0052 - N-Queens II (Hard)

Problem Link: https://leetcode.com/problems/n-queens-ii/

Description

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

8-queens

Given an integer n, return all distinct solutions to the n-queens puzzle.

Example:

Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/n-queens-ii/

namespace P51NQueensII
{
    class Solution
    {
        private:
        const char dot = '.';
        const char queen = 'Q';

        public:
        int totalNQueens(int n)
        {
            vector<string> result = vector<string>(n, string(n, dot));
            return Total(0, n, result, 0);
        }

        private:
        int Total(int total, int n, vector<string>& result, int row)
        {
            if (row == n)
            {
                return total + 1;
            }

            for (int col = 0; col < n; col++)
            {
                result[row][col] = queen;

                bool flag = true;

                for (int r = 0; r < row; r++)
                {
                    // 同列
                    if (result[r][col] == queen)
                    {
                        flag = false;
                        break;
                    }

                    int diff = row - r;
                    int left = col - diff;
                    int right = col + diff;

                    // 左上方斜线
                    if (left >= 0 && result[r][left] == queen)
                    {
                        flag = false;
                        break;
                    }

                    // 右上方斜线
                    if (right < n && result[r][right] == queen)
                    {
                        flag = false;
                        break;
                    }
                }

                if (flag)
                {
                    total = Total(total, n, result, row + 1);
                }

                result[row][col] = dot;
            }

            return total;
        }
    };
}

0053 - Maximum Subarray (Easy)

Problem Link: https://leetcode.com/problems/maximum-subarray/

Description

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Follow up:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/maximum-subarray/

namespace P53MaximumSubarray
{
    class Solution
    {
        public:
        int maxSubArray(vector<int>& nums)
        {
#if false // 穷举 exhaustion
            int maxVal = INT_MIN;
            for (int i = 0; i < nums.size(); i++)
            {
                int sum = 0;
                for (int j = i; j < nums.size(); j++)
                {
                    sum += nums[j];
                    maxVal = max(sum, maxVal);
                }
            }
            return maxVal;
#endif

#if true // O(n)
            int curVal = 0;
            int maxVal = INT_MIN;
            for (int i = 0; i < nums.size(); i++)
            {
                curVal = max(nums[i], curVal + nums[i]);
                maxVal = max(maxVal, curVal);
            }
            return maxVal;
#endif
        }
    };
}

0054 - Spiral Matrix (Medium)

Problem Link: https://leetcode.com/problems/spiral-matrix/

Description

Given a matrix of m x n elements ( m rows, n columns), return all elements of the matrix in spiral order.

Example 1:

Input:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]

Example 2:

Input:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/spiral-matrix/

namespace P54SpiralMatrix
{
    class Solution
    {
        private:
        enum Direction
        {
            Right,
            Down,
            Left,
            Up,
        };

        public:
        vector<int> spiralOrder(vector<vector<int>>& matrix)
        {
            vector<int> result;

            if (matrix.size() == 0 || matrix[0].size() == 0)
            {
                return result;
            }

            int size = matrix.size() * matrix[0].size();
            Direction dir = Direction::Right;
            int curRow = 0;
            int startRow = 0;
            int endRow = matrix.size() - 1;
            int curCol = 0;
            int startCol = 0;
            int endCol = matrix[0].size() - 1;

#if true // 每一圈为一个循环 O(n)
            while (startRow <= endRow && startCol <= endCol)
            {
                // Direction::Right
                for (curCol = startCol; curCol <= endCol; curCol++)
                {
                    result.push_back(matrix[startRow][curCol]);
                }

                // Direction::Down
                for (curRow = startRow + 1; curRow <= endRow; curRow++)
                {
                    result.push_back(matrix[curRow][endCol]);
                }

                if (startRow < endRow && startCol < endCol)
                {
                    // Direction::Left
                    for (curCol = endCol - 1; curCol >= startCol; curCol--)
                    {
                        result.push_back(matrix[endRow][curCol]);
                    }

                    // Direction::Up
                    for (curRow = endRow - 1; curRow > startRow; curRow--)
                    {
                        result.push_back(matrix[curRow][startCol]);
                    }
                }

                startCol++;
                endCol--;
                startRow++;
                endRow--;
            }
#endif

#if false // 每个节点为一个循环 O(n)
            for (int i = 0; i < size; i++)
            {
                result.push_back(matrix[curRow][curCol]);

                switch (dir)
                {
                    case Direction::Right:
                        if (curCol == endCol)
                        {
                            dir = Direction::Down;
                            endCol--;
                            curRow++;
                        }
                        else
                        {
                            curCol++;
                        }
                        break;
                    case Direction::Down:
                        if (curRow == endRow)
                        {
                            dir = Direction::Left;
                            endRow--;
                            curCol--;
                        }
                        else
                        {
                            curRow++;
                        }
                        break;
                    case Direction::Left:
                        if (curCol == startCol)
                        {
                            dir = Direction::Up;
                            startCol++;
                            curRow--;
                        }
                        else
                        {
                            curCol--;
                        }
                        break;
                    case Direction::Up:
                        if (curRow == startRow + 1)
                        {
                            dir = Direction::Right;
                            startRow++;
                            curCol++;
                        }
                        else
                        {
                            curRow--;
                        }
                        break;
                }
            }
#endif

            return result;

        }
    };
}

0055 - Jump Game (Medium)

Problem Link: https://leetcode.com/problems/jump-game/

Description

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

Example 1:

Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
             jump length is 0, which makes it impossible to reach the last index.

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/jump-game/

namespace P55JumpGame
{
    class Solution
    {
        public:
        bool canJump(vector<int>& nums)
        {
            if (nums.empty() || nums.size() == 1)
            {
                return true;
            }

            int curIndex = 0;
            int largest = 0;
            for (int i = 0; i < nums.size() - 1; i++)
            {
                largest = max(largest, i + nums[i]);
                if (i == curIndex)
                {
                    curIndex = largest;
                }

                if (curIndex >= nums.size() - 1)
                {
                    return true;
                }
            }

            return false;
        }
    };
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值