【Leetcode Summary】16-20题总结

本文深入解析LeetCode上的经典算法题目,包括3SumClosest、LetterCombinationsOfAPhoneNumber及4Sum等,提供详细的解决方案与代码实现,帮助读者理解和掌握算法设计与优化技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

16. 3Sum Closest

Medium

 

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

solution:找到三个相加和target最相近的数字。本质上和15题思路一样。让第一个数字先定下来,然后后面两个数字从两端开始

向中间循环,在这个题卡了因为一些简单的问题卡了好久。  这里不能随便对两端的指针进行++/--因为 这不同于相加等于0,   ++或者--可能会丢失某个数字

代码如下:

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {

        int res=nums[0] + nums[1] + nums[2];;
        int closest=INT_MAX ;
        sort(nums.begin(), nums.end());
        
    for (int i = 0; i < nums.size() - 2; ++i) {
            
            if (i > 0 && nums[i] == nums[i - 1]) continue;

            int left = i + 1, right = nums.size() - 1;
            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                int newDiff = abs(sum - target);
                if (closest > newDiff) {
                    closest = newDiff;
                    res = sum;
                }
           
                if(sum<target)
                    ++left;
                else --right;
            }
               
                
            }

        
        return res;
    }
};

17.17. Letter Combinations of a Phone Number

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

Example:

Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

solution:考虑给每个数字都做一个字典,然后递归调用每个数字就可以了,

这里稍微说一下递归函数:先写递归出口。然后再写递归

代码实现如下:

class Solution {
public:
   vector<string> letterCombinations(string digits) {
        if (digits.empty()) return {};
        vector<string> res;
        string dict[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        letterCombinationsDFS(digits, dict, 0, "", res);
        return res;
    }
    void letterCombinationsDFS(string digits, string dict[], int level, string out, vector<string> &res) {
        if (level == digits.size()) {res.push_back(out); return;}
        string str = dict[digits[level] - '0'];
        for (int i = 0; i < str.size(); ++i) {
            letterCombinationsDFS(digits, dict, level + 1, out + string(1, str[i]), res);
        }
    }
};

18. 4Sum

Given an array nums of n integers and an integer target, are there elements abc, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

The solution set must not contain duplicate quadruplets.

Example:

Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

solution:和3sum基本类似,遍历循环,先确定前两个数字。 后两个数字从两端开始向中间递归。

这里需要先用set<vector<int>>。因为四个数字不能保证没有重复。(第一个和第二个可能重复)

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        set<vector<int>> res;
        sort(nums.begin(),nums.end());

for (int i = 0; i < int(nums.size() - 3); ++i) {
            for (int j = i + 1; j < int(nums.size() - 2); ++j) {
                
                if (j > i + 1 && nums[j] == nums[j - 1]) continue;
                int left = j + 1, right = nums.size() - 1;
                
                while (left < right) {
                    int sum = nums[i] + nums[j] + nums[left] + nums[right];
                    if (sum == target) {
                        vector<int> out{nums[i], nums[j], nums[left], nums[right]};
                        res.insert(out);
                        ++left; --right;
                    } else if (sum < target) ++left;
                    else --right;
                }
            }
        }
        return vector<vector<int>>(res.begin(),res.end());
    }
};

19.Remove Nth Node From End of List

Example:

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:

Given n will always be valid.

Follow up:

Could you do this in one pass?

solution:删除从结尾开始数的第n个数字,希望能一次循环就删去,需要绑定一个前指针,让后指针先移动n次,这样再一起移动,当后指针移动到结尾时,前指针则为倒数第N个

代码略去

20.Valid Parentheses

Given a string containing just the characters '('')''{''}''['and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

solution:检测括号是否成对匹配,最直接的想法就是遇到左括号,就压入栈,遇到右括号,看栈顶是不是对应的左括号,如果是出栈,如果不是,返回false。最后检查栈是否为空,如果空则匹配,否则返回false

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值