[Solutions to LeetCode Algorithm Series] Questions 46~50

LeetCode 46. Full arrangement (medium)

[Title description]

Given an array without duplicate numbers nums, return all possible permutations . You can return answers in any order .

【Example 1】

输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

【Example 2】

输入:nums = [0,1]
输出:[[0,1],[1,0]]

【Example 3】

输入:nums = [1]
输出:[[1]]

【hint】

1 ≤ n u m s . l e n g t h ≤ 6 1\le nums.length\le 6 1nums.length6
− 10 ≤ nums [ i ] ≤ 10 -10\le nums[i]\le 1010nums[i]
numsAll integers in 10 are different from each other

【analyze】


Fully arranged naked questions, DFS introductory questions, do not need to be explained too much. Since the questions ensure that each number is different from each other, each bit in the binary system of an integer can be used to indicate whether a certain number has been used, omitting Additional space overhead for open tagged arrays.

Of course, you can also use next_permutationfunctions to kill instantly, but you still need to know how to rub your hands during the interview~


【Code】

[ next_permutationFunction implementation]

class Solution {
    
    
public:
    vector<vector<int>> res;

    vector<vector<int>> permute(vector<int>& nums) {
    
    
        sort(nums.begin(), nums.end());
        do {
    
    
            res.push_back(nums);
        } while (next_permutation(nums.begin(), nums.end()));
        return res;
    }
};

[DFS implementation]

class Solution {
    
    
public:
    vector<vector<int>> res;
    vector<int> v;

    vector<vector<int>> permute(vector<int>& nums) {
    
    
        dfs(nums, 0, 0);
        return res;
    }

    void dfs(vector<int>& nums, int u, int state)  // state二进制的第i位表示i是否已被使用
    {
    
    
        if (u == nums.size()) {
    
     res.push_back(v); return; }
        for (int i = 0; i < nums.size(); i++)
            if (!(state >> nums[i] + 10 & 1))  // 判断state的第i位是否为1,注意将nums[i]映射成0~20
            {
    
    
                v.push_back(nums[i]);
                dfs(nums, u + 1, state | 1 << nums[i] + 10);
                v.pop_back();
            }
    }
};

LeetCode 47. Full Arrangement II (Medium)

[Title description]

Given a sequence that may contain repeated numbers , return all non-repeating permutations numsin any order .

【Example 1】

输入:nums = [1,1,2]
输出:[[1,1,2],[1,2,1],[2,1,1]]

【Example 2】

输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

【hint】

1 ≤ n u m s . l e n g t h ≤ 8 1\le nums.length\le 8 1nums.length8
− 10 ≤ nums [ i ] ≤ 10 -10\le nums[i]\le 1010nums[i]10

【analyze】


The difference between this question and the previous question is that numbers may be repeated, so you need to consider how to control the searched sequence from repeating. For the same numbers, we should specify their order, such as sorting them in ascending order or descending order, so that the arrangement of the same numbers will only have one corresponding relationship.

How to achieve this operation? We sort the array first. We need to ensure that the relative positions of the same numbers in the answer are the same as the original array. Therefore, when we enumerate each number nums[i], if nums[i] == nums[i - 1]and nums[i - 1]has not been used, then nums[i]it cannot be used. stateWe use binary ii in this questionThe i bit indicatesnums[i]whether it is used.


【Code】

class Solution {
    
    
public:
    vector<vector<int>> res;
    vector<int> v;

    vector<vector<int>> permuteUnique(vector<int>& nums) {
    
    
        sort(nums.begin(), nums.end());  // 先排好序
        dfs(nums, 0, 0);
        return res;
    }

    void dfs(vector<int>& nums, int u, int state)
    {
    
    
        if (u == nums.size()) {
    
     res.push_back(v); return; }
        for (int i = 0; i < nums.size(); i++)
            // 如果当前数和前一个数相等但是前一个数没被用过那么当前数也不能用
            if (i && nums[i] == nums[i - 1] && !(state >> i - 1 & 1)) continue;
            else if (!(state >> i & 1))  // 判断第i个数是否被使用
            {
    
    
                v.push_back(nums[i]);
                dfs(nums, u + 1, state | 1 << i);
                v.pop_back();
            }
    }
};

LeetCode 48. Rotate Image (Medium)

[Title description]

Given a n × ntwo-dimensional matrix matrixrepresenting an image. Please rotate the image 90 degrees clockwise.
You have to rotate the image in place , which means you need to modify the input 2D matrix directly. Please do not use another matrix to rotate the image.

【Example 1】

Insert image description here

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[[7,4,1],[8,5,2],[9,6,3]]

【Example 2】

Insert image description here

输入:matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
输出:[[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]

【hint】

n = = m a t r i x . l e n g t h = = m a t r i x [ i ] . l e n g t h n == matrix.length == matrix[i].length n==matrix.length==ma t r i x [ i _ _ l e n g th 1 ≤ n ≤ 20 1\and n\ and
1n20
− 1000 ≤ m a t r i x [ i ] [ j ] ≤ 1000 -1000\le matrix[i][j]\le 1000 1000matrix[i][j]1000

【analyze】


Let’s first give an example of the transformation process:

1 2 3      1 4 7      7 4 1
4 5 6  =>  2 5 8  =>  8 5 2
7 8 9      3 6 9      9 6 3

The process is very simple, but it is really difficult to figure it out if you have not been exposed to similar problems. First flip along the main diagonal, and then flip along the central axis of the column.


【Code】

class Solution {
    
    
public:
    void rotate(vector<vector<int>>& matrix) {
    
    
        int n = matrix.size();
        // 沿对角线翻转
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j < n; j++)
                swap(matrix[i][j], matrix[j][i]);
        // 沿列中轴线翻转
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n >> 1; j++)
                swap(matrix[i][j], matrix[i][n - 1 - j]);
    }
};

LeetCode 49. Anagram grouping (medium)

[Title description]

You are given an array of strings, and you are asked to combine the anagrams together. The list of results can be returned in any order.
An anagram is a new word obtained by rearranging all the letters of the source word.

【Example 1】

输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
输出: [["bat"],["nat","tan"],["ate","eat","tea"]]

【Example 2】

输入: strs = [""]
输出: [[""]]

【Example 3】

输入: strs = ["a"]
输出: [["a"]]

【hint】

1 ≤ s t r s . l e n g t h ≤ 1 0 4 1\le strs.length\le 10^4 1strs.length104
0 ≤ s t r s [ i ] . l e n g t h ≤ 100 0\le strs[i].length\le 100 0strs[i].length100
strs[i] contains only lowercase letters

【analyze】


We can sort each string in lexicographic order, so that if two strings contain the same characters, the sorted strings must also be the same, and then we can use a hash table to record each type of string.


【Code】

class Solution {
    
    
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
    
    
        vector<vector<string>> res;
        unordered_map<string, int> st;  // 记录每一类的下标
        int idx = 0;
        for (auto s: strs)
        {
    
    
            string t = s;
            sort(t.begin(), t.end());
            if (!st[t]) st[t] = ++idx, res.push_back(vector<string> {
    
     s });
            else res[st[t] - 1].push_back(s);  // 注意vector中下标从0开始
        }
        return res;
    }
};

LeetCode 50. Pow(x, n) (medium)

[Title description]

implementation pow(x, n), that is, computing an xinteger npower function of (i.e., xnx^nxn)。

【Example 1】

输入:x = 2.00000, n = 10
输出:1024.00000

【Example 2】

输入:x = 2.10000, n = 3
输出:9.26100

【Example 3】

输入:x = 2.00000, n = -2
输出:0.25000
解释:2-2 = 1/22 = 1/4 = 0.25

【hint】

− 100.0 < x < 100.0 -100.0 < x < 100.0 100.0<x<100.0
− 2 31 ≤ n ≤ 2 31 − 1 -2^{31}\le n\le 2^{31}-1231n2311
n is an integer
that is eitherxnonzero, orn > 0.
− 1 0 4 ≤ xn ≤ 1 0 4 -10^4\le x^n\le 10^4104xn104

【analyze】


Quick naked power problem, unify nnConvert n to a non-negative number and then solve it, and finally usennThe result can be modified by the positive and negative values ​​of n (x − n = 1 xnx^{-n}=\frac {1}{x^n}xn=xn1). Note that if nnIf nINT_MIN is directly converted to a positive number, it will overflow, so it needs to be turned onlong long.


【Code】

class Solution {
    
    
public:
    double myPow(double x, int n) {
    
    
        double res = 1;
        for (long long k = abs((long long)n); k; k >>= 1)
        {
    
    
            if (k & 1) res *= x;
            x *= x;
        }
        if (n < 0) res = 1 / res;
        return res;
    }
};

おすすめ

転載: blog.csdn.net/m0_51755720/article/details/132631468