摘要: 题目链接 解题思路:就是一个递归。弄清楚题目意思,n=1时,就返回1,然后n=2时,返回上一个结果,上一个结果是一个1,所以就是11,然后n=3,返回上一个结果,就是两个1,所以就是21 代码 class Solution { public: string countAndSay(int n) { 阅读全文
posted @ 2024-12-18 17:34 ouyangxx 阅读(14) 评论(0) 推荐(0)
摘要: 题目链接 解题思路:整体思路是一个回溯,一行一行填。然后填的过程中可以剪枝,也就是我们可以添加一些约束条件,不能填的时候,就没必要去尝试了(还有一种填法,全部填完之后,再检查是否合规,这样复杂度太大了)。具体细节看代码。 代码 class Solution { public: // 0~8行,0~8 阅读全文
posted @ 2024-12-18 17:13 ouyangxx 阅读(26) 评论(0) 推荐(0)
摘要: 题目链接 解题思路:整体框架就是二分,只是找到了target后,还要继续查找。分两次查找,第一次是「找到等于target最左的位置」,第二次是「找到等于target最右的位置」 代码 class Solution { public: vector<int> searchRange(vector<in 阅读全文
posted @ 2024-12-18 14:53 ouyangxx 阅读(7) 评论(0) 推荐(0)
摘要: 题目链接 解题思路:题目意思是,把原来的有序数组分成两半,左边的放右边来,右边的放左边去,然后数组中是否存在target这个数,存在则返回其下标。 要求时间复杂度O(logn) 整体的框架还是二分查找,但是在查找过程中,我们总能得到「一边」是有序的,例如在整体[L, R]上,划分成两半是[L, x] 阅读全文
posted @ 2024-12-18 14:33 ouyangxx 阅读(29) 评论(0) 推荐(0)
摘要: 题目链接 解题思路:保证一个有效区,当发现一个「新数」时,就扩大有效区。 怎么判断是否是一个新数?来到一个i位置,往左边看,如果相等,则i++,一直到不想等为止。为什么可以这样?因为是有序的。 代码 class Solution { public: int removeDuplicates(vect 阅读全文
posted @ 2024-12-18 11:27 ouyangxx 阅读(18) 评论(0) 推荐(0)
摘要: 题目链接 解题思路:每次从全局的拿一个最小值出来,每个链表的「头」,都是最小的,所以,我们可以使用一个小根堆(优先级队列),存放每个链表当前的「头」,然后弹出一个全局最小的节点出来,然后把该节点的next放回小根堆,供之后使用。 注意,压入小根堆时,要保证不为nullptr。 代码 /** * De 阅读全文
posted @ 2024-12-18 11:12 ouyangxx 阅读(30) 评论(0) 推荐(0)
摘要: 题目链接 解题思路:从左往右生成,生成的过程中,保证右括号不能比左括号多。 代码 class Solution { public: // 总共有n个括号对,left_res就是左括号还能使用的数目,right_res就是右括号还能使用的数目 // 要保证左括号大于等于右括号数目,即left_res 阅读全文
posted @ 2024-12-18 10:59 ouyangxx 阅读(14) 评论(0) 推荐(0)
摘要: 题目链接 解题思路:括号匹配问题,优先想到栈。 代码 class Solution { public: bool isValid(string s) { stack<char> st; for (auto &ch : s) { // 如果是右括号,那么必须得有一个相匹配的左括号 if (ch == 阅读全文
posted @ 2024-12-18 10:51 ouyangxx 阅读(13) 评论(0) 推荐(0)
摘要: 题目链接 解题思路:可以定义一个node节点,然后一个cur节点,node节点先走n-1步,然后cur和node同时走,如果node->next == null了,那么cur就是被删除的节点,此时,我们用pre节点指向cur的前一个节点(node和cur在走的时候,pre也跟着走),就可以删除cur 阅读全文
posted @ 2024-12-18 10:46 ouyangxx 阅读(22) 评论(0) 推荐(0)
摘要: 题目链接 解题思路:一个简单的回溯题目。 代码 class Solution { public: map<char, string> table{ {'2', "abc"}, {'3', "def"}, {'4', "ghi"}, {'5', "jkl"}, {'6', "mno"}, {'7', 阅读全文
posted @ 2024-12-18 10:39 ouyangxx 阅读(26) 评论(0) 推荐(0)
摘要: 题目链接 解题思路:没啥可说的,按照要求一个个字符处理 代码 class Solution { public: int romanToInt(string s) { int ans = 0; int len = s.length(); map<char, int> table{ {'I', 1}, 阅读全文
posted @ 2024-12-18 09:58 ouyangxx 阅读(10) 评论(0) 推荐(0)
摘要: 题目链接 解题思路:整数转罗马数字,可以理解为一个一个「数」,有一个转换表,从高位依次往低位「数」,直接看代码更清晰 代码 class Solution { public: string intToRoman(int num) { // 转换表 vector<pair<int, string>> t 阅读全文
posted @ 2024-12-18 09:21 ouyangxx 阅读(18) 评论(0) 推荐(0)
摘要: 题目链接 解题思路:用第一个字符串的每个字符,逐个比较其他字符串,注意别越界就行 代码 class Solution { public: string longestCommonPrefix(vector<string>& strs) { string ans = ""; int len = str 阅读全文
posted @ 2024-12-18 08:57 ouyangxx 阅读(10) 评论(0) 推荐(0)