算法岗面试准备LeetCode刷题专栏

LeetCode刷题专栏C++

  • LeetCode 1 两数之和
    • code1
    • code2
  • LeetCode 2 两数相加
  • LeetCode 3 无重复字符的最长子串
    • code1
    • code2
  • LeetCode 4 寻找两个有序数组的中位数
  • LeetCode 5 最长回文子串
    • code1
    • code2
    • code3
    • 测试代码
  • LeetCode 6 Z 字形变换
  • LeetCode 7 整数反转
  • LeetCode 8 字符串转换整数 (atoi)
  • code1
  • code2
  • LeetCode 9 回文数
  • LeetCode 11 盛水最多的容器
  • LeetCode 17 电话号码的字母组合
    • code1
    • code2
    • code3
  • LeetCode 19 删除链表的倒数第N个节点
  • LeetCode 20 有效的括号
  • LeetCode 21 合并两个有序链表
    • 图解
    • code1
    • code2
  • LeetCode 22 括号生成
  • LeetCode 27 移除元素
  • LeetCode 34 在排序数组中查找元素的第一个和最后一个位置
  • LeetCode 35 搜索插入位置(二分法)
  • LeetCode 38 报数
  • LeetCode 39 组合总和
  • LeetCode 42 接雨水
  • LeetCode 43 字符串相乘
  • LeetCode 44 通配符匹配
  • LeetCode 45 跳跃游戏2
  • LeetCode 46 全排列
    • 图解
    • code1
    • code2
    • code3
  • LeetCode 48 旋转图像
  • LeetCode 49 字母异位词分组
  • LeetCode 50 Pow(x, n)
  • LeetCode 51 N皇后
  • LeetCode 53 最大子序和
  • LeetCode 54 螺旋矩阵
  • LeetCode 56 合并区间
    • code1
    • code2
  • LeetCode 62 不同路径
  • LeetCode 64 最小路径和
  • LeetCode 69 x的平方根(二分法)
    • code1
    • code2
  • LeetCode 72 编辑距离
  • LeetCode 77 组合(DFS)
  • LeetCode 78 子集
    • code1
    • code2
    • code3
  • LeetCode 79 单词搜索
  • LeetCode 83 删除排序链表中的重复元素
  • LeetCode 88 合并两个有序数组
  • LeetCode 90 子集2
  • LeetCode 93 复原IP地址
    • code1
    • code2
  • LeetCode 94 二叉树中序遍历
    • code(非递归)
    • code(递归)
  • LeetCode 96 不同的二叉搜索树
  • LeetCode 100 相同的树
  • LeetCode 101 对称二叉树
  • LeetCode 104 树的最大深度
    • code1
    • code2
  • LeetCode 105 从前序和中序遍历构建二叉树
  • LeetCode 107 二叉树的层次遍历 II
  • LeetCode 108 将有序数组转化为二叉搜索树
  • LeetCode 111 二叉树的最小深度
  • LeetCode 113 路径总和2
  • LeetCode 114 二叉树展开为链表(DFS)
  • LeetCode 121 买卖股票的最佳时机
  • LeetCode 122 买卖股票的最佳时机2
  • LeetCode 130 被围绕的区域(DFS)
  • LeetCode 131 分隔回文串
  • LeetCode 136 只出现一次的数
  • LeetCode 137 只出现一次的数2
  • LeetCode 141 环形链表
  • LeetCode 144 二叉树的前序遍历
    • code(非递归)
    • code(递归)
  • LeetCode 145 二叉树的后序遍历
    • code(非递归)
    • code(递归)
  • LeetCode 153 寻找旋转排序数组中的最小值
  • LeetCode 154 寻找旋转排序数组中的最小值2
  • LeetCode 160 相交链表
  • LeetCode 174 地下城游戏
  • LeetCode 200 岛屿数量(DFS)
    • code1
    • code2
    • code3
  • LeetCode 206 反转链表
    • code1
    • code2
    • code3
  • LeetCode 217 存在重复元素
  • LeetCode 230 二叉搜索树中第K小的元素
  • LeetCode 234 回文链表
  • LeetCode 236 二叉树的最近公共祖先
  • LeetCode 239 滑动窗口最大值
    • code1
  • LeetCode 257 二叉树的所有路径
  • LeetCode 263 丑数
  • LeetCode 264 丑数2
  • LeetCode 275 H指数 II
  • LeetCode 278 第一个错误的版本
  • LeetCode 279 完全平方数
  • LeetCode 306 累加数
  • 路径总和3
  • LeetCode 363 矩形区域不超过 K 的最大数值和
    • code1(TLE)
    • code2
    • code3
  • LeetCode 382 链表随机节点
  • LeetCode 415 字符串相加
  • LeetCode 416 分割等和子集
    • 解法一
    • 解法二
  • LeetCode 443 压缩字符串
  • LeetCode 445 两数相加 II
  • LeetCode 456 132模式
  • LeetCode 474 一和零
  • LeetCode 509 斐波那契数
  • LeetCode 543 二叉树的直径(DFS)
  • LeetCode 707 设计链表
  • LeetCode 718 最长重复子数组
  • LeetCode 733 图像渲染
  • LeetCode 784 字母大小写全排列
  • LeetCode 921 使括号有效的最少添加
  • LeetCode 1074 元素和为目标值的子矩阵数量
  • LeetCode 1389 按既定顺序创建目标数组
  • LeetCode 1390 四因数

LeetCode 1 两数之和

code1

#include
#include
#include
#include

using namespace std;

	class Solution {
	public:
		vector twoSum(vector& nums, int target) {
			unordered_map m;
			for (int i = 0; i < nums.size(); i++) {
				if (m.count(target - nums[i])) {
					return { i, m[target - nums[i]] };
				}
				m[nums[i]] = i;
			}
			return {};
		}
	};

int main() {
	vector nums = { 2, 7, 11, 15 };
	int target = 9;
	vector res = Solution().twoSum(nums, target);
	cout << "nums1_index = " << res[0] << endl; 
	cout << "nums2_index = " << res[1] << endl;
	system("pause");
	return 0;
}

code2

#include 
#include 
#include 

using namespace std;

typedef pair PII;

class Solution {
public:
    vector twoSum(vector& nums, int target) {
        int n = nums.size();
        unordered_map m;
        vector res;
        for(int i = 0; i < n; i++){
            if(m.count(target-nums[i])) {
                res.push_back({i, m[target-nums[i]]});
            }  
            m[nums[i]] = i;  
        }
        return res;
    }
};

int main() {
    int target = 9;
    vector nums = {2, 7, 5, 4, 1, 8, 12, 47};
    vector res = Solution().twoSum(nums, target);
    for(int i = 0; i < res.size(); i++)
    cout << res[i].first <<" "<< res[i].second << endl;
	return 0;
}

LeetCode 2 两数相加

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode *dummy = new ListNode(-1), *cur = dummy;
        int carry = 0;
        while(l1||l2){
            int val1 = l1 ? l1->val:0;
            int val2 = l2 ? l2->val:0;
            int sum = val1 + val2 + carry;
            carry = sum /10;
            cur->next = new ListNode(sum%10);
            cur = cur->next;
            if(l1) l1 = l1->next;
            if(l2) l2 = l2->next;
        }
        if(carry) cur->next = new ListNode(1);
        return dummy->next;
        
    }
};

LeetCode 3 无重复字符的最长子串

code1

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int res = 0, left = -1;
        int n = s.size();
        unordered_map m(n);
        for(int i = 0; i < n; i++){
            if(m.count(s[i])&&m[s[i]] > left){
                left = m[s[i]]; 
            }
            m[s[i]] = i;
            res = max(res, i-left);
        }
        return  res;
    }
};

code2

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if(!s.size()) return 0;
        int n = s.size();
        vector dp(n);
        int j = 0;
        bool flag = false;
        int temp = 0;
        int res = 1;
        for(int i = 1; i < n; i++){ 
            flag = false;
            j = temp;
            for(j; j < i; j++){
                if(s[i] == s[j]){
                    dp[i] = 1;  
                    temp = j+1;
                    flag = true;
                }
            }
            if(!flag){
                 dp[i]  = i - temp + 1; 
            }
            res = max(res, dp[i]);
        }
        return res;
    }
};

LeetCode 4 寻找两个有序数组的中位数

class Solution {
public:
    double findMedianSortedArrays(vector& nums1, vector& nums2) {
        int m = nums1.size(), n = nums2.size(), left = (m+n+1) / 2, right = (m+n+2) / 2;
        return(findKth(nums1, 0, nums2, 0, left) + findKth(nums1, 0, nums2, 0, right)) / 2.0;

    }
    int findKth(vector& nums1, int i, vector& nums2, int j, int k){
        if(i >= nums1.size()) return nums2[j+k-1];
        if(j >= nums2.size()) return nums1[i+k-1];
        if(k == 1) return min(nums1[i], nums2[j]);
        int midval1 = (i + k/2 -1 < nums1.size()) ? nums1[i + k / 2 -1] : INT_MAX;
        int midval2 = (j + k/2 -1 < nums2.size()) ? nums2[j + k / 2 -1] : INT_MAX;
        if(midval1 < midval2){
            return findKth(nums1, i + k / 2, nums2, j, k - k / 2);
        } else {
            return findKth(nums1, i, nums2, j + k / 2, k - k / 2);
        }
    }
};

LeetCode 5 最长回文子串

code1

class Solution {
public:
    string longestPalindrome(string s) {
        if(s.size()<2) return s;
        int n = s.size(), maxLen = 0, start = 0;
        for(int i = 0; i < n-1; i++){
            searchP(s, i, i, start, maxLen);
            searchP(s, i, i+1, start, maxLen);
        }
        return s.substr(start, maxLen);
    }
    void searchP(string s, int left, int right, int& start, int& maxLen){
        while(left>=0&&right

code2

class Solution {
public:
    string longestPalindrome(string s) {
        if(s.empty()) return "";
        int n = s.size(), dp[n][n] = {0}, left = 0, len = 1;
        for(int i = 0; i < n; i++){
            dp[i][i] = 1;
            for(int j = 0; j < i; j++){
                dp[j][i] = (s[j] == s[i] && (i-j<2||dp[j+1][i-1]));
                if(dp[j][i]&&len

code3

class Solution {
public:
    string longestPalindrome(string s) {
        int n = s.size();
        if(n<2) return s;
        string res = "";
        vector<int> f(n+1, 1);  
        for(int i = 0; i < n-1; i++){
            int odd = 1, even = 1;
            for(int j = i; j >= 0; j--){
                if(odd == 1 && s[j] != s[2*i-j]) odd = 0; 
                if(even ==1 && s[j] != s[2*i-j+1]) even = 0; 
                if(even == 1) {
                    f[i] = 2*(i-j)+2;
                     if(f[i] > res.size()){
                         res = s.substr(j, f[i]);
                     } 
                }
                if(odd == 1){
                    f[i] = 2*(i-j)+1;
                     if(f[i] > res.size()){
                         res = s.substr(j, f[i]);
                     }
                } 
                if(odd==1||even==1) continue;
                break;   
            }
        }
        return res;
    }
};

测试代码

#include
#include
#include

using namespace std;

class Solution {
public:
	string maxP(string s) {
		if (s.size() < 2) return s;
		int n = s.size(), start = 0, maxLen = 0;
		for (int i = 0; i < n - 1; i++) {
			searchP(s, i, i, start, maxLen);
			searchP(s, i, i + 1, start, maxLen);

		}
		return s.substr(start, maxLen);
	
	}
	void searchP(string s, int left, int right, int& start, int& maxLen) {
		while (left >= 0 && right < s.size()&&s[left] == s[right]) {
			--left, ++right;
		}
		if (maxLen < right - left - 1) {
			start = left + 1;
			maxLen = right - left - 1;
		}
	}
};
int main() {
	string s = "aba";
	string res = Solution().maxP(s);
	cout << res << endl;
	system("pause");
	return 0;
}

LeetCode 6 Z 字形变换

class Solution {
public:
    string convert(string s, int numRows) {
        if(numRows <= 1) return s;
        string res;
        int size = 2*numRows-2, n = s.size();
        for(int i = 0; i < numRows; i++){
            for(int j = i; j < n; j += size){
                res +=s[j];
                int pos = j + size -2*i;
                if(i != 0 && i != numRows - 1 && pos < n) res += s[pos];
            }
        }
        return res;
    }
};

LeetCode 7 整数反转

#include

using namespace std;

class Solution {
public:
	int reverse(int x) {
		int res = 0;
		while (x) {
			if (abs(res) > INT_MAX) return 0;
			res = res * 10 + x % 10;
			x /= 10;
		}
		return res;
	}
};

int main() {
	int x = 1463847412; //214748364
	int result = Solution().reverse(x);
	cout << result;
	system("pause");
	return 0;
}

LeetCode 8 字符串转换整数 (atoi)

code1

class Solution {
public:
    int myAtoi(string str) {
        if(str.empty()) return 0;
        int n = str.size();
        long long res = 0;
        int k = 0;
        bool isminus = false;
        while(k < n && str[k]==' ') k++;
        if(str[k] == '+') k++;
        else if(str[k] == '-') isminus = true, k++;
        while(str[k] >= '0' && str[k] <= '9'){
            if (res > INT_MAX / 10 || (res == INT_MAX / 10 && str[k] - '0' > 7)) {
                return (isminus == false) ? INT_MAX : INT_MIN;
            }
            res = res*10 + str[k]-'0', k++;  
        }  
        if(isminus) res *= -1;
        return res;
    }
};

code2

class Solution {
public:
    int myAtoi(string str) {
        if (str.empty()) return 0;
        int sign = 1, base = 0, i = 0, n = str.size();
        while (i < n && str[i] == ' ') ++i;
        if (i < n && (str[i] == '+' || str[i] == '-')) {
            sign = (str[i++] == '+') ? 1 : -1;
        }
        while (i < n && str[i] >= '0' && str[i] <= '9') {
            if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) {
                return (sign == 1) ? INT_MAX : INT_MIN;
            }
            base = 10 * base + (str[i++] - '0');
        }
        return base * sign;
    }
};

LeetCode 9 回文数

class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0) return false;
        int div = 1;
        while(x/div >= 10) div *= 10;
        while(x > 0){
            int left = x / div;
            int right = x % 10;
            if(left != right) return false;
            x = ( x % div ) / 10;
            div /= 100;   
        }
        return true;
    }
};

LeetCode 11 盛水最多的容器

class Solution {
public:
    int maxArea(vector& height) {
        int res = 0, i = 0, j = height.size()-1;
        while(i < j) {
            res = max(res, min(height[i], height[j])*(j-i));
            height[i] < height[j] ? i++: j--;    
        }
        return res;
    }
};

LeetCode 17 电话号码的字母组合

code1

#include
#include
#include

using namespace std;

class Solution {
public:
	vector letterCombinations(string digits) {
		if (digits.empty()) return {};
		vector res;
		vector dict{ " ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
		letterCombinationsDFS(digits, dict, 0, "", res);
		return res;
	}
	void letterCombinationsDFS(string& digits, vector& dict, int level, string out, vector& 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 + str[i], res);
		}
	}
};
int main() {
	vector res = Solution().letterCombinations("234");
	for (int i = 0; i < res.size(); i++)
		cout << res[i] << endl;
	system("pause");
	return 0;
}

code2

#include
#include
#include
#include

using namespace std;

class Solution {
private:
	vector res;
	const string letterMap[10] = {
		" ",
		"",
		"abc",
		"def",
		"ghi",
		"jkl",
		"mno",
		"pqrs",
		"tuv",
		"wxyz"
	};
	void findCombinations(const string& digits, int index, const string& s) {
		if (index == digits.size()) {
			res.push_back(s); 
			return;
		}
			
		char c = digits[index];
		assert( c >= '0' && c <= '9' && c != '1');
		string letters = letterMap[c - '0'];
		for (int i = 0; i < letters.size(); ++i) {
			findCombinations(digits,index+1,s+letters[i]);
		}
	}
public:
	vector letterCombinations(string digits) {
		res.clear();
		if (digits == "") return res;
		findCombinations(digits,0,"");
		return res;
	}
};
int main() {
	string digits = "23";
	vector res = Solution().letterCombinations(digits);
	for (int i = 0; i < res.size(); ++i) {
		cout << res[i] << endl;
	}
	system("pause");
	return 0;
}

code3

class Solution {
public:
    vector letterCombinations(string digits) {
        vector chars = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        if(digits.empty()) return vector();
        vectorstate(1, "");     
        for(auto u : digits){
            vector now;
            for(auto c : chars[u-'2'])
                for(auto s : state)
                    now.push_back(s+c);
            state = now;
        }
        return state;
    }
};

LeetCode 19 删除链表的倒数第N个节点

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if(!head->next) return NULL;
        auto pre = head, cur = head;
        for(int i = 0; i < n; i++) cur = cur->next;
        if(!cur) return head->next;
        while(cur->next){
            cur=cur->next;
            pre=pre->next;
        }
        pre->next = pre->next->next;
        return head;
    }
    
};

LeetCode 20 有效的括号

#include
#include
#include

using namespace std;

class Solution {
public:
	bool isValid(string s) {
		stack parentheses;
		for (int i = 0; i < s.size(); ++i) {
			if (s[i] == '(' || s[i] == '[' || s[i] == '{') parentheses.push(s[i]);
			else {
				if (parentheses.empty()) return false;
				if (s[i] == ')' && parentheses.top() != '(') return false;
				if (s[i] == ']' && parentheses.top() != '[') return false;
				if (s[i] == '}' && parentheses.top() != '{') return false;
				parentheses.pop();
			}
		}
		return parentheses.empty();
	}
};

int main() {
	string s = "()[]{}";
	bool res = Solution().isValid(s);
	if (res == true)
		cout << "true" << endl;
	else
		cout << "false" << endl;
	system("pause");
	return 0;
}


LeetCode 21 合并两个有序链表

图解

算法岗面试准备LeetCode刷题专栏_第1张图片

code1

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode dummy(0);
        ListNode *tail = &dummy;
        while(l1&&l2){
            if(l1->valval){
                tail->next = l1;
                l1 = l1->next;
            }
            else{
                tail->next = l2;
                l2 = l2->next;
            }
            tail = tail->next;          
        }
        if(l1) tail->next = l1;
        if(l2) tail->next = l2;
        return dummy.next;
    }
};

code2

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode *dummy = new ListNode(-1), *cur = dummy;
        while (l1 && l2) {
            if (l1->val < l2->val) {
                cur->next = l1;
                l1 = l1->next;
            } else {
                cur->next = l2;
                l2 = l2->next;
            }
            cur = cur->next;
        }
        cur->next = l1 ? l1 : l2;
        return dummy->next;
    }
};

LeetCode 22 括号生成

class Solution {
public:
    vector generateParenthesis(int n) {
        vector res;
        generateParenthesisDFS(n, n, "", res);
        return res;
    }
    void generateParenthesisDFS(int left, int right, string out, vector&res){
        if(left>right) return;
        if(left==0&&right==0) res.push_back(out);
        else{
            if(left>0) generateParenthesisDFS(left-1,right,out+'(', res);
            if(right) generateParenthesisDFS(left, right-1, out+')', res);
        }
    }
};

LeetCode 27 移除元素

class Solution {
 
public:
    int removeElement(vector& nums, int val) {
 
        int j = 0;
        for( int i = 0 ; i < nums.size() ; i ++ )
            if( nums[i] != val )
                nums[j++] = nums[i];
 
        return j;
    }
};

LeetCode 34 在排序数组中查找元素的第一个和最后一个位置

class Solution {
public:
    vector searchRange(vector& nums, int target) {
        if(nums.empty()) return {-1,-1};
        int l = 0, r = nums.size()-1;
        while(l>1;
            if(target <= nums[mid]) r = mid;
            else l = mid+1;
        }
        int res = l;
        if(nums[res] != target) return{-1, -1};
        l = 0, r = nums.size()-1;
        while(l < r){
            int mid = l+r+1>>1;
            if(target >= nums[mid])  l= mid;
            else r = mid -1;
        }
        return {res, l};
    }
};

LeetCode 35 搜索插入位置(二分法)

#include
#include

using namespace std;

class Solution {
public:
	int searchInsert(vector& nums, int target) {
		if (nums.empty()) return 0;
		int l = 0, r = nums.size() - 1;
		while (l < r) {
			int mid = (l + r) >> 1;
			if (nums[mid] == target) 
				return mid;
			else if (nums[mid] < target) 
				l = mid + 1;
			else r = mid;
		}
		return r;
	}
};
int main() {
	vector nums = {1,3,5,6};
	int target = 2;
	int res = Solution().searchInsert(nums, target);
	cout << res << endl;
	system("pause");
	return 0;
}

LeetCode 38 报数

class Solution {
public:
    string countAndSay(int n) {
        if (n <= 0) return "";
        string res = "1";
        while (--n) {
            string cur = "";
            for (int i = 0; i < res.size(); ++i) {
                int cnt = 1;
                while (i + 1 < res.size() && res[i] == res[i + 1]) {
                    ++cnt;
                    ++i;
                }
                cur += to_string(cnt) + res[i];
            }
            res = cur;
        }
        return res;
    }
};

LeetCode 39 组合总和

#include
#include
#include

using namespace std;

class Solution {
public:
	vector> combinationSum(vector& candidates, int target) {
		vector> res;
		vector out;
		combinationSumDFS(candidates, target, 0, out, res);
		return res;
	}
	void combinationSumDFS(vector& candidates, int target, int start, vector& out, vector>& res) {
		if (target < 0) return;
		if (target == 0) { res.push_back(out); return; }
		for (int i = start; i < candidates.size(); ++i) {
			out.push_back(candidates[i]);
			combinationSumDFS(candidates, target - candidates[i], i, out, res);
			out.pop_back();
		}
	}
};
int main() {
	vector candidates = {2,3,6,7};
	int target = 7;
	vector> result = Solution().combinationSum(candidates, target);
	for (int i = 0; i < result.size(); i++) {
		for (int j = 0; j < result[i].size(); j++) {
			cout << result[i][j] << " ";
		}
		cout << endl;
	}
	system("pause");
	return 0;
}

LeetCode 42 接雨水

class Solution {
public:
    int trap(vector& height) {
        int res = 0, mx = 0, n = height.size();
        vector dp(n, 0);
        for(int i = 0; i < n; i++){
            dp[i] = mx;
            mx = max(mx, height[i]);
        }
        mx = 0;
        for(int i = n - 1; i >= 0; i--){
            dp[i] = min(dp[i], mx);
            mx = max(mx, height[i]);
            if(dp[i] > height[i]) res += dp[i] - height[i];
        }
        return res;
    }
};

LeetCode 43 字符串相乘

class Solution {
public:
    string multiply(string num1, string num2) {
        string res  = "";
        int m = num1.size(), n = num2.size();
        vector vals(m+n);
        for(int i = m-1; i >= 0; i--){
            for(int j = n-1; j >= 0; j--){
                   int p1 = i + j, p2 = i + j + 1;
                   int sum = (num1[i]-'0')*(num2[j]-'0')+vals[p2];
                   vals[p1] += sum/10;
                   vals[p2] = sum % 10;
                
            } 
        }
        for(int val : vals){
            if(!res.empty() || val != 0) res.push_back(val+'0');
        }
        return res.empty() ? "0" : res;
    }
};

LeetCode 44 通配符匹配

class Solution {
public:
    bool isMatch(string s, string p) {
        int i = 0, j = 0, iStar = -1, jStar = -1;
        while(i < s.size()){
            if(s[i] == p[j]||p[j] == '?'){
                i++; j++;
            }else if(p[j] == '*'){
                iStar = i;
                jStar = j++;
            }
            else if(iStar>=0){
                i = ++iStar;
                j = jStar+1;
            }else  return false; 
        }
        while(j < p.size()&&p[j] == '*') ++j;
        return  j == p.size(); 
    }
};

LeetCode 45 跳跃游戏2

class Solution {
public:
    int jump(vector& nums) {
        int res = 0, n = nums.size(),  i = 0, cur = 0;
        while(cur < n-1){
            ++res;
            int pre = cur;
            for(;  i <= pre; i++){
                cur = max(cur, i+nums[i]);
            }
        }
        return res;
    }
};

LeetCode 46 全排列

图解

在这里插入图片描述

code1

#include
#include

using namespace std;

class Solution {
public:
	vector> permute(vector& num) {
		vector> res;
		permuteDFS(num, 0, res);
		return res;
	}
	void permuteDFS(vector& num, int start, vector>& res) {
		if (start >= num.size()) res.push_back(num);
		for (int i = start; i < num.size(); ++i) {
			swap(num[start], num[i]);
			permuteDFS(num, start + 1, res);
			swap(num[start], num[i]);
		}
	}
};
int main() {
	vector num{1,2,3};
	vector> res = Solution().permute(num);
	for (int i = 0; i < res.size(); i++) {
		for (int j = 0; j < res[i].size(); j++)
			cout << res[i][j];
		cout << endl;
	}	
	system("pause");
	return 0;
}

code2

#include 
#include 
#include 

using namespace std;

class Solution {
private:
	vector> res;
	vector used;
	void generatePermutation(const vector& nums, int index, vector& p) {
		if (index == nums.size()) { 
			res.push_back(p); 
			return; 
		}
		for (int i = 0; i < nums.size(); i++) {
			if (!used[i]) {
				p.push_back(nums[i]);
				used[i] = true;
				generatePermutation(nums, index + 1, p);
				p.pop_back();
				used[i] = false;
			}
		}
		return;
	}
public:
	vector> permute(vector& nums) {
		res.clear();
		if (nums.size() == 0)
			return res;
		used = vector(nums.size(), false);
		vector p;
		generatePermutation(nums, 0, p);
		return res;
	}
};
int main() {
	vector num{1, 2, 3};
	vector> res = Solution().permute(num);
	for (int i = 0; i < res.size(); i++) {
		for (int j = 0; j < res[i].size(); j++)
			cout << res[i][j];
		cout << endl;
	}
	system("pause");
	return 0;
}

code3

#include
#include

using namespace std;

vector path;
vector st;

void dfs(int n, int u) {
	
	if (u == n+1) {
		for (auto x : path) cout << x << " ";
		cout << endl;
	}
	for (int i = 1; i <= n; i++) {
		if (!st[i]) {
			st[i] = true;
			path.push_back(i);
			dfs(n, u + 1);
			path.pop_back();
			st[i] = false;
		}

	}
}

int main() {
	int n;
	cin >> n;
	st = vector(n, false);
	dfs(n, 1);
	system("pause");
	return 0;
}

LeetCode 48 旋转图像

class Solution {
public:
    void rotate(vector>& matrix) {
        int n  = matrix.size();
        for(int i = 0;  i < n; i++){
            for(int j = 0; j < i; j++){
                swap(matrix[i][j], matrix[j][i]);
            } 
        }
         for(int i = 0;  i < n; i++){
            for(int j = 0; j < n/2 ; j++){
                swap(matrix[i][j], matrix[i][n-1-j]);
            }
        }
    }
};

LeetCode 49 字母异位词分组

class Solution {
public:
    vector> groupAnagrams(vector& strs) {
        vector> res;
        unordered_map> m;
        for(string str:strs){
            string t = str;
            sort(t.begin(), t.end());
            m[t].push_back(str);
        }
        for(auto a:m){
            res.push_back(a.second);
        }
        return res;
    }
};

LeetCode 50 Pow(x, n)

class Solution {
public:
    double myPow(double x, int n) {
        if(n<0) return 1/pow(x, n);
        else return pow(x, n);
    }
    double pow (double x, int n){
        if(n == 0)  return 1;
        double y = pow(x, n/2);
        if(n % 2 == 0) return y*y;
        else return y*y*x;  
    }
};

LeetCode 51 N皇后

class Solution {
public:
    static const int N = 1010;
    bool col[N], dg[N], udg[N];
    vector> solveNQueens(int n) {
       
        vector> res;
        vector queens(n,string(n, '.'));
        dfs(0, queens, res);
        return res;
    }
    void dfs(int u, vector& queens, vector>& res){
        int n = queens.size();
        if(u == n){
            res.push_back(queens);
            return;
        }
        for(int i = 0; i < n; i++)
            if(!col[i]&&!dg[u+i]&&!udg[n-u+i]){
                queens[u][i] = 'Q';
                col[i] = dg[u+i] = udg[n-u+i] = true;
                dfs(u+1, queens, res);
                col[i] = dg[u+i] = udg[n-u+i] = false;
                queens[u][i] = '.';
            }
    }
};

LeetCode 53 最大子序和

class Solution {
public:
    int maxSubArray(vector& nums) {
        int res = nums[0], cursum = 0;
        for(auto x : nums){
            cursum = max(cursum+x, x);
            res = max(res, cursum);
        }
        return res;
    }
};

LeetCode 54 螺旋矩阵

class Solution {
public:
    vector spiralOrder(vector>& matrix) {
        if(matrix.empty()||matrix[0].empty()) return {};
        int m = matrix.size(), n = matrix[0].size();
        vector res;
        int up = 0, down = m-1, left = 0, right = n-1;
        while(true){
            for(int j = left; j <= right; j++) res.push_back(matrix[up][j]);
            if(++up > down) break;
            for(int i = up; i <= down; i++) res.push_back(matrix[i][right]);
            if(--right= left; j--) res.push_back(matrix[down][j]);
            if(--down < up) break;
            for(int i = down; i >= up; i-- ) res.push_back(matrix[i][left]);
            if(++left>right) break;
        }
        return res;
    }
};

LeetCode 56 合并区间

code1

class Solution{
    public:
    vector> merge(vector> &intervals){
        if(intervals.empty()) return {};
        sort(intervals.begin(), intervals.end());
        vector> res = {intervals[0]};
        for(int i=0; i

code2

#include 

using namespace std;

const int N=100000+100;

pair a[N];
int n,cnt;
int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
        cin>>a[i].first>>a[i].second;
    sort(a+1,a+1+n);
    cnt=n;
    for(int i=1;i=a[i+1].first)
        {
            cnt--;
            a[i+1].first=a[i].first;
            a[i+1].second=max(a[i+1].second,a[i].second);
        }
    cout<

LeetCode 62 不同路径

class Solution {
public:
    int uniquePaths(int m, int n) {
    vector> f(m, vector(n, 0));
    f[0][0] = 1;
    for(int i = 0; i < m; i++){
        for(int j = 0; j < n; j++){
            if(i>0) f[i][j] += f[i-1][j];
            if(j>0) f[i][j] += f[i][j-1];
        }
        }
       return f[m-1][n-1]; 
    }
};

LeetCode 64 最小路径和

class Solution {
public:
    int minPathSum(vector>& grid) {
        int m = grid.size(), n = grid[0].size();
        int dp[m][n];
        dp[0][0] = grid[0][0];
        for(int i = 1; i < m; i++) dp[i][0] = grid[i][0]+dp[i-1][0];
        for(int j = 1; j < n; j++) dp[0][j] = grid[0][j]+dp[0][j-1];
        for(int i = 1; i < m; i++){
            for(int j = 1; j < n; j++){
                dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]; 
            }   
        }
        return dp[m-1][n-1];    
    }
};

LeetCode 69 x的平方根(二分法)

code1

#include
#include
#include

using namespace std;

class Solution {
public:
	int mySqrt(int x) {
		if (x <= 1) return x;
		int left = 0, right = x;
		while (left < right) {
			int mid = left + (right - left) / 2;
			if (x / mid >= mid) left = mid + 1;
			else right = mid;
		}
		return right - 1;
	}
};
int main() {
	int x = 8;
	int res = Solution().mySqrt(x);
	cout << res << endl;
	system("pause");
	return 0;
}

code2

class Solution {
public:
    int mySqrt(int x) {
        int l = 0, r = x;
        while(l < r){
            int mid = l + r + 1 >> 1;
            if(mid <= x / mid) l = mid;
            else r = mid - 1;
        }
        return l;
    }
};

LeetCode 72 编辑距离

class Solution {
public:
    int minDistance(string word1, string word2) {
        int m = word1.size(), n = word2.size();
        vector> dp(m+1, vector(n+1));
        for(int i = 0; i <= m; ++i) dp[i][0] = i;
        for(int j = 0; j <= n; ++j) dp[0][j] = j;
        for(int i = 1; i <= m; ++i)
            for(int j = 1; j <= n; ++j){
                if(word1[i-1] == word2[j-1]) dp[i][j] = dp[i-1][j-1];
                else dp[i][j] = min(dp[i-1][j-1], min(dp[i-1][j], dp[i][j-1]))+1;      
            }
        return dp[m][n];
    }
};

LeetCode 77 组合(DFS)

class Solution {
public:
    vector> ans;
    vector> combine(int n, int k) {
        vector path;
        dfs(n, k, 1, path);
        return ans;
    }
    void dfs(int n, int k, int t, vector path){
        if(!k){
            ans.push_back(path);
            return;
        } 
        for(int i = t; i <= n; i++){
            path.push_back(i); 
            dfs(n, k-1, i+1, path);
            path.pop_back();
        }  
    }
};

LeetCode 78 子集

code1

#include
#include

using namespace std;

class Solution {
private:
	void generation(int i, vector& nums, vector& item, vector>& result) {
		if (i>=nums.size()) {
			return;	
		}
		
		item.push_back(nums[i]);
		result.push_back(item);
		generation(i + 1, nums, item, result);
		item.pop_back();
		generation(i + 1, nums, item, result);	
	}
public:
	vector> subsets(vector& nums) {
		vector item;
		vector> result;
		result.push_back(item);
		generation(0, nums, item, result);
		return result;
	}
};
int main() {
	vector nums;
	nums.push_back(1);
	nums.push_back(2);
	nums.push_back(3);
	vector> result = Solution().subsets(nums);
	for (int i = 0; i < result.size(); i++) {
		for (int j = 0; j < result[i].size(); j++) {
			cout << result[i][j] << " ";
		}
		cout << endl;
	}
	system("pause");
	return 0;
}

code2

#include
#include

using namespace std;

class Solution {
private:
	void generation(int pos, vector& nums, vector& item, vector>& result) {
		result.push_back(item);
		for (int i = pos; i < nums.size(); i++) {
			item.push_back(nums[i]);
			generation(i + 1, nums, item, result);
			item.pop_back();
		}
	}
public:
	vector> subsets(vector& nums) {
		vector item;
		vector> result;
		generation(0, nums, item, result);
		return result;
	}
};
int main() {
	vector nums;
	nums.push_back(1);
	nums.push_back(2);
	nums.push_back(3);
	vector> result = Solution().subsets(nums);
	for (int i = 0; i < result.size(); i++) {
		for (int j = 0; j < result[i].size(); j++) {
			cout <

code3

public:
    vector> subsets(vector& nums) {
        vector> res;
        for (int i = 0; i < 1 << nums.size(); i ++ )
        {
            vector now;
            for (int j = 0; j < nums.size(); j ++ )
                if (i >> j & 1)
                    now.push_back(nums[j]);
            res.push_back(now);
        }
        return res;
    }
};

LeetCode 79 单词搜索

#include
#include
#include

using namespace std;

class Solution {
public:
	bool exist(vector>& board, string word) {
		if (board.empty() || board[0].empty()) return false;
		int m = board.size(), n = board[0].size();
		vector> visited(m, vector(n));
		for (int i = 0; i < m; ++i) {
			for (int j = 0; j < n; ++j) {
				if (search(board, word, 0, i, j, visited)) return true;
			}
		}
		return false;
	}
	bool search(vector>& board, string word, int idx, int i, int j, vector>& visited) {
		if (idx == word.size()) return true;
		int m = board.size(), n = board[0].size();
		if (i < 0 || j < 0 || i >= m || j >= n || visited[i][j] || board[i][j] != word[idx]) return false;
		visited[i][j] = true;
		bool res = search(board, word, idx + 1, i - 1, j, visited)
			|| search(board, word, idx + 1, i + 1, j, visited)
			|| search(board, word, idx + 1, i, j - 1, visited)
			|| search(board, word, idx + 1, i, j + 1, visited);
		visited[i][j] = false;
		return res;
	}
};
int main() {
	vector> board = 
	        {
		    {'A', 'B', 'C', 'E'},
			{'S', 'F', 'C', 'S'},
			{'A', 'D', 'E', 'E'}
	        };
	string word = "ABCCED";
	bool res = Solution().exist(board, word);
	cout << res << endl; 
	system("pause");
	return 0;
}

LeetCode 83 删除排序链表中的重复元素

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(!head) return head;
        ListNode *p = head;
        while(p->next){
            if(p->val==p->next->val) p->next = p->next->next;  
            else p = p->next;
        }
    return head;
    }
};

LeetCode 88 合并两个有序数组

class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        int p1 = m-1, p2 = n-1, cur = m+n-1;
        while(p1 >= 0 && p2 >= 0){
            if(nums1[p1]<nums2[p2]) nums1[cur--] = nums2[p2--];
            else nums1[cur--] = nums1[p1--];
        }
        if(p2>=0) for(int k = p2; k>=0; k--) nums1[cur--] = nums2[p2--];
    }
};

LeetCode 90 子集2

#include
#include
#include

using namespace std;

class Solution {
public:
	vector> subsetsWithDup(vector &S) {
		if (S.empty()) return {};
		vector> res;
		vector out;
		sort(S.begin(), S.end());
		getSubsets(S, 0, out, res);
		return res;
	}
	void getSubsets(vector &S, int pos, vector &out, vector> &res) {
		res.push_back(out);
		cout << endl;
		for (int i = pos; i < S.size(); ++i) {
			out.push_back(S[i]);
			getSubsets(S, i + 1, out, res);
			out.pop_back();
			while (i + 1 < S.size() && S[i] == S[i + 1]) 
				++i;
		}
	}
};
int main() {
	vector nums = {2,1,2,2};
	vector> result = Solution().subsetsWithDup(nums);
	for (int i = 0; i < result.size(); i++) {
		for (int j = 0; j < result[i].size(); j++) {
			cout << result[i][j] << " ";
		}
		cout << endl;
	}
	system("pause");
	return 0;
}

LeetCode 93 复原IP地址

code1

#include
#include
#include
#include

using namespace std;

class Solution {
public:
	vector restoreIpAddresses(string s) {
		vector res;
		restore(s, 4, "", res);
		return res;
	}
	void restore(string s, int k, string out, vector &res) {
		if (k == 0) {
			if (s.empty()) res.push_back(out);
		}
		else {
			for (int i = 1; i <= 3; ++i) {
				if (s.size() >= i && isValid(s.substr(0, i))) {
					if (k == 1) restore(s.substr(i), k - 1, out + s.substr(0, i), res);
					else restore(s.substr(i), k - 1, out + s.substr(0, i) + ".", res);
				}
			}
		}
	}
	bool isValid(string s) {
		if (s.empty() || s.size() > 3 || (s.size() > 1 && s[0] == '0')) return false;
		int res = atoi(s.c_str());
		return res <= 255 && res >= 0;
	}
};
int main() {
	string s = "25525511135";
	vector result = Solution().restoreIpAddresses(s);
	for (int i = 0; i < result.size(); i++) {
		cout << result[i] << endl;
	}
	system("pause");
	return 0;
}

code2

class Solution {
    public:
        vector restoreIpAddresses(const string& s) {
        vector result;
        vector ip; 
        dfs(s, ip, result, 0);
        return result;
        }
        void dfs(string s, vector& ip, vector &result, size_t start) {
            if (ip.size() == 4 && start == s.size()) { 
            result.push_back(ip[0] + '.' + ip[1] + '.' + ip[2] + '.' + ip[3]);
            return;
            }
            if (s.size() - start > (4 - ip.size()) * 3)
                return;
            if (s.size() - start < (4 - ip.size()))
                return;
            int num = 0;
            for (size_t i = start; i < start + 3; i++) {
                num = num * 10 + (s[i] - '0');
                if (num < 0 || num > 255) continue; 
                ip.push_back(s.substr(start, i - start + 1));
                dfs(s, ip, result, i + 1);
                ip.pop_back();
                if (num == 0) break;
            }
        }
};

LeetCode 94 二叉树中序遍历

code(非递归)

class Solution {
public:
    vector inorderTraversal(TreeNode* root) {
        vector res;
        stack s;
        TreeNode *p = root;
        while (!s.empty() || p) {
            if (p) {
                s.push(p);
                p = p->left;
            } else {
                p = s.top(); s.pop();
                res.push_back(p->val);
                p = p->right;
            }
        }
        return res;
    }
};

code(递归)

class Solution {
public:
    vector inorderTraversal(TreeNode *root) {
        vector res;
        inorder(root, res);
        return res;
    }
    void inorder(TreeNode *root, vector &res) {
        if (!root) return;
        if (root->left) inorder(root->left, res);
        res.push_back(root->val);
        if (root->right) inorder(root->right, res);
    }
};

LeetCode 96 不同的二叉搜索树

class Solution {
public:
    int numTrees(int n) {
        vector dp(n+1);
        dp[0] = dp[1] = 1;
        for(int i =2; i<=n; i++)
            for(int j = 0; j < i; j++)
                dp[i] += dp[j]*dp[i-j-1];
        return dp[n]; 
    }
};

LeetCode 100 相同的树

class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if(p==NULL&&q==NULL)
        return true;
        if(p==NULL&&q!=NULL)
        return false;
        if(p!=NULL&&q==NULL)
        return false;
        return p->val==q->val&&isSameTree(p->left, q->left)&&isSameTree(p->right, q->right);
    }
};

LeetCode 101 对称二叉树

class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        if(!root) return true;
        return dfs(root->left, root->right);
    }
    bool dfs(TreeNode* p, TreeNode* q){
        if(!p||!q) return !p&&!q;
        if(p->val!=q->val) return false;
        return dfs(p->left, q->right)&&dfs(p->right, q->left);
    }
};

LeetCode 104 树的最大深度

code1

class Solution {
public:
    int maxDepth(TreeNode* root) {
        int ans = dfs(root); 
        return ans;     
    }
    int dfs(TreeNode* root){
        if(!root) return 0;
        return max(dfs(root->left),  dfs(root->right)) + 1;
     }
};

code2

class Solution {
public:
    int maxDepth(TreeNode* root) {
        int ans = dfs(root); 
        return ans;     
    }
    int dfs(TreeNode* root){
        if(!root) return 0;
        int d1 = 0, d2 = 0;
        if(root->left) d1 = dfs(root->left);
        if(root->right) d2 = dfs(root->right);
        return max(d1, d2) + 1;
     }
};

LeetCode 105 从前序和中序遍历构建二叉树

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    map hash;
    vector preorder, inorder;
    TreeNode* buildTree(vector& pre, vector& in) {
     preorder = pre, inorder = in;
     for(int i = 0; i < inorder.size(); i++) hash[inorder[i]] = i;
     return dfs(0, preorder.size()-1, 0, inorder.size()-1);
    }
    TreeNode* dfs(int pl, int pr, int il, int ir){
        if(pl>pr) return nullptr;
        auto root = new TreeNode(preorder[pl]);
        int k = hash[root->val];
        auto left = dfs(pl+1, pl+k-il, il, k-1);
        auto right = dfs(pl+k-il+1, pr, k+1, ir);
        root->left = left, root->right = right;
        return root;  
    } 
};

LeetCode 107 二叉树的层次遍历 II

class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        
        queue<TreeNode*> q;
        vector<vector<int>> ans;
        if(!root) return ans;
        vector<int> level; 
        q.push(root);
        q.push(nullptr);
        while(q.size()){
            TreeNode* t = q.front();
            q.pop();
            if(!t){
              ans.push_back(level);
              level.clear();
              if(q.back()) q.push(nullptr);
              continue;
            }
            level.push_back(t->val);
            if(t->left) q.push(t->left);
            if(t->right) q.push(t->right);
        }
        return vector<vector<int>>(ans.rbegin(), ans.rend());
        }    
};

LeetCode 108 将有序数组转化为二叉搜索树

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedArrayToBST(vector& nums) {
       return dfs(0, nums.size()-1, nums);
    }
    TreeNode* dfs(int l, int r, vector& nums){
        if(l>r) return nullptr;
        int mid = (l+r)/2;
        
        TreeNode* root = new TreeNode(nums[mid]);
        TreeNode* left = dfs(l, mid-1, nums);
        TreeNode* right = dfs(mid+1, r, nums);
        root->left = left, root->right = right;
        return root;
    }
};

LeetCode 111 二叉树的最小深度

 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode* root) {
        if(!root) return 0;
        int left = minDepth(root->left);
        int right = minDepth(root->right);
        if(!left||!right) return left+right+1;
        return min(left, right)+1;
        
    }
};

LeetCode 113 路径总和2

class Solution {
public:
    vector> res;
    vector> pathSum(TreeNode* root, int sum) {
        vector path;
        dfs(root, sum, 0, path);
        return res;
    }
    void dfs(TreeNode* root, int sum, int curSum, vector& path){
        if(!root) return;
        path.push_back(root->val);
        curSum += root->val;
        if(curSum == sum&&!root->left&&!root->right) res.push_back(path);
        dfs(root->left, sum, curSum, path);
        dfs(root->right, sum, curSum, path);
        path.pop_back();
    }
};

LeetCode 114 二叉树展开为链表(DFS)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode* root) {
        TreeNode* now = root;
        while(now){
            if(now->left){
                TreeNode* p = now->left;
                while(p->right) p = p->right;
                p->right = now->right;
                now->right = now->left;
                now->left = nullptr;
            }
            now = now->right;
        } 
    }
};

LeetCode 121 买卖股票的最佳时机

class Solution {
public:
    int maxProfit(vector& prices) {
        int res = 0, buy = INT_MAX;
        for (int price : prices) {
            buy = min(buy, price);
            res = max(res, price - buy);
        }
        return res;
    }
};

LeetCode 122 买卖股票的最佳时机2

class Solution {
public:
    int maxProfit(vector& prices) {
        int res = 0, n = prices.size();
        for(int i = 0; i < n-1; i++){
            if(prices[i]

LeetCode 130 被围绕的区域(DFS)

class Solution {
public:
    vector> st;
    int n, m;
    void solve(vector>& board) {
        if(board.empty() || board[0].empty()) return;
        n = board.size(), m = board[0].size();
        for(int i = 0; i temp;
            for(int j = 0; j>&board, int x, int y){
        st[x][y] = true;
        int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
        for(int i = 0; i < 4; i++){
            int a = x + dx[i], b = y + dy[i];
            if(a >= 0 && a < n && b >= 0 && b < m && !st[a][b] && board[a][b] == 'O')
                dfs(board, a, b);  
        }  
    }
};

LeetCode 131 分隔回文串

如果原字符串是 abcd, 那么访问顺序为: a -> b -> c -> d -> cd -> bc -> bcd-> ab -> abc -> abcd, 这是对于没有两个或两个以上子回文串的情况。那么假如原字符串是 aabc,那么访问顺序为:a -> a -> b -> c -> bc -> ab -> abc -> aa -> b -> c -> bc -> aab -> aabc。
在这里插入图片描述

#include
#include
#include

using namespace std;

class Solution {
public:
	vector> partition(string s) {
		vector> res;
		vector out;
		helper(s, 0, out, res);
		return res;
	}
	void helper(string s, int start, vector& out, vector>& res) {
		if (start == s.size()) { 
			res.push_back(out); 
			return;
		}
		for (int i = start; i < s.size(); ++i) {
			if (!isPalindrome(s, start, i)) continue;
			out.push_back(s.substr(start, i - start + 1));
			helper(s, i + 1, out, res);
			out.pop_back();
		}
	}
	bool isPalindrome(string s, int start, int end) {
		while (start < end) {
			if (s[start] != s[end]) return false;
			++start; --end;
		}
		return true;
	}
};

int main() {
	string s = "aabc";

	vector> res = Solution().partition(s);
	for (int i = 0; i < res.size(); i++) {
		for (int j = 0; j < res[i].size(); j++) {
			cout << res[i][j] << " ";
		}
	}
	system("pause");
	return 0;
}

LeetCode 136 只出现一次的数

class Solution {
public:
    int singleNumber(vector& nums) {
        int res = 0;
        for(auto x : nums) res ^=x;
        return res;
    }
};

LeetCode 137 只出现一次的数2

class Solution {
public:
    int singleNumber(vector& nums) {
        int res = 0;
        for(int i = 0; i < 32; i ++){
            int sum = 0;
            for(int j = 0; j < nums.size(); j++){
                sum += (nums[j]>>i) & 1;
            }
            res |= (sum%3)<

LeetCode 141 环形链表

class Solution {
public:
    bool hasCycle(ListNode *head) {
        ListNode *slow = head, *fast = head;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast) return true;
        }
        return false;
    }
};

LeetCode 144 二叉树的前序遍历

code(非递归)

class Solution {
public:
    vector preorderTraversal(TreeNode* root) {
        vector res;
        stack s;
        TreeNode *p = root;
        while (!s.empty() || p) {
            if (p) {
                s.push(p);
                res.push_back(p->val);
                p = p->left;
            } else {
                TreeNode *t = s.top(); s.pop();
                p = t->right;
            }
        }
        return res;
    }
};

code(递归)

class Solution {
public:
	vector postorderTraversal(TreeNode *root) {
		vector res;
		inorder(root, res);
		return res;
	}
	void inorder(TreeNode *root, vector &res) {
		if (!root) return;
		if (root->left) inorder(root->left, res);
		if (root->right) inorder(root->right, res);
		res.push_back(root->val);
	}
};

LeetCode 145 二叉树的后序遍历

code(非递归)

#include
#include
#include

using namespace std;

struct TreeNode {
	int val;
	TreeNode* left;
	TreeNode* right;
	TreeNode(int data) : val(data), left(nullptr), right(nullptr) {}
};
void connectNode(TreeNode* pParent, TreeNode* left, TreeNode* right) {
	if (pParent != nullptr){
		pParent->left = left;
		pParent->right = right;
	}
}

class Solution {
public:
	vector postorderTraversal(TreeNode* root) {
		vector res;
		stack s;
		TreeNode *p = root;
		while (!s.empty() || p) {
			if (p) {
				s.push(p);
				res.insert(res.begin(), p->val);
				p = p->right;
			}
			else {
				TreeNode *t = s.top(); s.pop();
				p = t->left;
			}
		}
		return res;
	}
};

int main() {
	TreeNode* pNode1 = new TreeNode(1);
	TreeNode* pNode2 = new TreeNode(2);
	TreeNode* pNode3 = new TreeNode(3);
	TreeNode* pNode4 = new TreeNode(4);
	TreeNode* pNode5 = new TreeNode(5);
	TreeNode* pNode6 = new TreeNode(6);
	TreeNode* pNode7 = new TreeNode(7);

	connectNode(pNode1, pNode2, pNode3);
	connectNode(pNode2, pNode4, pNode5);
	connectNode(pNode3, nullptr, pNode6);
	connectNode(pNode5, pNode7, nullptr);

	vector res = Solution().postorderTraversal(pNode1);
	for (int i = 0; i < res.size(); i++) {
		cout << res[i] << " ";
	}
	cout << endl;
	system("pause");
	return 0;
}


code(递归)

class Solution {
public:
	vector postorderTraversal(TreeNode *root) {
		vector res;
		inorder(root, res);
		return res;
	}
	void inorder(TreeNode *root, vector &res) {
		if (!root) return;
		if (root->left) inorder(root->left, res);
		if (root->right) inorder(root->right, res);
		res.push_back(root->val);
	}
};

LeetCode 153 寻找旋转排序数组中的最小值

#include
#include
#include

using namespace std;

class Solution {
public:
	int findMin(vector &num) {
		int left = 0, right = num.size() - 1;
		if (num[left] > num[right]) {
			while (left != (right - 1)) {
				int mid = (left + right) / 2;
				if (num[left] < num[mid]) left = mid;
				else right = mid;
			}
			return min(num[left], num[right]);
		}
		return num[0];
	}
};
int main() {
	vector nums = { 4,5,6,7,0,1,2 };
	int result = Solution().findMin(nums);
	cout << result << endl;
	system("pause");
	return 0;
}

LeetCode 154 寻找旋转排序数组中的最小值2

#include
#include
#include

using namespace std;

class Solution {
public:
	int findMin(vector &nums) {
		if (nums.empty()) return 0;
		int left = 0, right = nums.size() - 1, res = nums[0];
		while (left < right - 1) {
			int mid = left + (right - left) / 2;
			if (nums[left] < nums[mid]) {
				res = min(res, nums[left]);
				left = mid + 1;
			}
			else if (nums[left] > nums[mid]) {
				res = min(res, nums[right]);
				right = mid;
			}
			else ++left;
		}
		res = min(res, nums[left]);
		res = min(res, nums[right]);
		return res;
	}
};
int main() {
	vector nums = { 10,1,10,10,10 };
	int result = Solution().findMin(nums);
	cout << result << endl;
	system("pause");
	return 0;
}

LeetCode 160 相交链表

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        if (!headA || !headB) return NULL;
        ListNode *a = headA, *b = headB;
        while (a != b) {
            a = a ? a->next : headB;
            b = b ? b->next : headA;
        }
        return a;
    }
};

LeetCode 174 地下城游戏

class Solution {
public:
    int calculateMinimumHP(vector<vector<int>>& dungeon) {
        int m = dungeon.size(), n = dungeon[0].size();
        vector<vector<int>> dp(m + 1, vector<int>(n + 1, INT_MAX));
        dp[m][n - 1] = 1; dp[m - 1][n] = 1;
        for (int i = m - 1; i >= 0; --i) {
            for (int j = n - 1; j >= 0; --j) {
                dp[i][j] = max(1, min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]);
                //cout << "i:" << i << "j:" << j << "dp:" << dp[i][j] << endl;
            }
        }
        return dp[0][0];
    }
};

LeetCode 200 岛屿数量(DFS)

code1

class Solution {
public:
    int n, m;
    int numIslands(vector>& grid) {
        if(grid.empty() || grid[0].empty()) return 0;
        n = grid.size(), m = grid[0].size();
        int res = 0;
        for(int i = 0; i < n; i ++ ){
            for(int j = 0; j < m; j++){
                if(grid[i][j] == '1'){
                res++;
                dfs(grid,i,j);
                } 
            }  
        }
         return res;  
    }
    void dfs(vector>& grid, int x, int y){
        int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
        grid[x][y] = '0';
        for(int i = 0; i < 4; i++){
            int a = x + dx[i], b = y + dy[i];
            if(a >= 0 && a < n && b >= 0 && b < m && grid[a][b] == '1')
                dfs(grid, a, b);
        }     
    }
};

code2

class Solution {
public:
    int res = 0;
    int numIslands(vector>& grid) {
        if(grid.empty()||grid[0].empty()) return 0;
        int m = grid.size(), n = grid[0].size();
        vector> visited(m, vector(n));
        for(int i = 0; i < m; i++)
            for(int j = 0; j < n; j++){
                //visited[i][j] = true;
                if(grid[i][j] == '0' || visited[i][j]) continue;
                dfs(grid, visited, i, j);
                ++res;
            } 
        return res;
    }
    void dfs(vector>& grid, vector>& visited, int x, int y){
        
        visited[x][y] = true; 
        int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
        for(int k = 0; k < 4; k++){
            int a = x + dx[k], b = y + dy[k];
            if(a>=0&&a=0&&b

code3

class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        if(grid.empty()) return 0;
        int n = grid.size(), m = grid[0].size();
        int cnt = 0;
        for(int i = 0; i < n; i++)
            for(int j = 0; j < m; j++)
                if(grid[i][j]-'0' == 1){
                    cnt++;
                    dfs(i, j, grid); 
                }
        return cnt;
    }
    void dfs(int i, int j, vector<vector<char>>& grid){
        int n = grid.size(), m = grid[0].size();
        grid[i][j] = '0';
        if(i!=0 && grid[i-1][j] - '0'== 1) dfs(i-1, j, grid);
        if(j!=m-1 && grid[i][j+1] - '0' == 1) dfs(i, j+1, grid);
        if(i!=n-1 && grid[i+1][j] - '0' == 1) dfs(i+1, j, grid);
        if(j!=0 && grid[i][j-1] - '0' == 1) dfs(i, j-1, grid);
        return;
    } 
};

LeetCode 206 反转链表

code1

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(!head){
            return nullptr;
        }
        ListNode* first = head;//始终指向原链表的首位元素
        ListNode* target = head->next;//始终指向即将要放到当前链表首元素之前的目标元素
        while(target != nullptr){
            first->next = target->next;
            ListNode* temp = target->next;
            target->next = head;
            head = target;
            target = temp;
        }
        return head;
    }
    };

code2

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* pre = NULL;
        ListNode* cur = head;
        ListNode* post = NULL;
        while(cur!=NULL){
            post = cur->next;
            cur->next = pre;
            pre = cur;
            cur = post;
        }
        return pre;
    }
};

code3

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
    ListNode* pre = nullptr;
    auto cur = head;
    while(cur){
        auto temp = cur->next;
        cur->next = pre;
        pre = cur;
        cur = temp;
    }
    return pre;
    } 
};

LeetCode 217 存在重复元素

class Solution {
public:
    bool containsDuplicate(vector& nums) {
        unordered_map h;
        for(int i = 0; i < nums.size(); i++){
            if(++h[nums[i]]>1) return true;  
        }
        return false;
    }
};

LeetCode 230 二叉搜索树中第K小的元素

class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        return dfs(root, k);
    }
    int dfs(TreeNode* root, int& k){
        if(!root) return -1;
        int val = dfs(root->left, k);
        if(k == 0) return val;
        if(--k == 0) return root->val;
        return dfs(root->right, k);
    }
};

LeetCode 234 回文链表

class Solution {
public:
    bool isPalindrome(ListNode* head) {
     ListNode* cur = head;
     stackst;
     while(cur){
         st.push(cur->val);
         cur = cur->next;
     }
        while(head){
            int t = st.top(); st.pop();
            if(head->val!=t) return false;
            head = head->next;
        }
        return true;
    }
};

LeetCode 236 二叉树的最近公共祖先

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(!root) return nullptr;
        if(root==p||root==q) return root;
        TreeNode* left = lowestCommonAncestor(root->left, p, q);
        TreeNode* right = lowestCommonAncestor(root->right, p, q);
        
        if(left&&right) return root;
        if(left) return left;
        else return right;    
    }
};

LeetCode 239 滑动窗口最大值

code1

class Solution {
public:
    vector maxSlidingWindow(vector& nums, int k) {
        vector res;
        multiset st;
        for(int i = 0; i < nums.size(); i++){
            if(i>=k) st.erase(st.find(nums[i-k]));
            st.insert(nums[i]);
            if(i>=k-1) res.push_back(*st.rbegin());
        }
       return res; 
    }
};

LeetCode 257 二叉树的所有路径

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector ans;
    vector binaryTreePaths(TreeNode* root) {
        string path;
        dfs(root, path);
        return ans;  
    }
    void dfs(TreeNode* root, string path){
        if(!root) return;
        if(!root->left && !root->right) {
            ans.push_back(path+to_string(root->val));
            return;
        }
        if(root->left) dfs(root->left, path+to_string(root->val)+"->");
        if(root->right) dfs(root->right, path+to_string(root->val)+"->");
    }  
};

LeetCode 263 丑数

class Solution {
public:
    bool isUgly(int num) {
        if (num <= 0)
            return false;
        while (num % 5 == 0)
            num = num / 5;
        while (num % 3 == 0)
            num = num / 3;
        while (num % 2 == 0)
            num = num / 2;
        return num == 1;
    }
};

LeetCode 264 丑数2

class Solution {
public:
    int nthUglyNumber(int n) {
        vector uglyNumbers;
        uglyNumbers.push_back(1);
        int index2 = 0;//2 3 5三个指针
        int index3 = 0;
        int index5 = 0;
        for(int i = 1;i

LeetCode 275 H指数 II

class Solution {
public:
    int hIndex(vector& citations) {
        int l = 0, r = citations.size();
        while(l < r){
            int mid = l+r+1ll >>1;
            if(citations[citations.size()-mid] >= mid) l = mid;
            else r = mid - 1;
        }
       return l; 
    }
};

LeetCode 278 第一个错误的版本

// Forward declaration of isBadVersion API.
bool isBadVersion(int version);

class Solution {
public:
    int firstBadVersion(int n) {
        int l = 0, r = n;
        while(l < r){
            int mid = l + (r-l>>2);
            if(isBadVersion(mid) == true) r = mid;
            else l = mid+1;
        }
        return l;
    }
};

LeetCode 279 完全平方数

class Solution {
public:
    int numSquares(int n) {
        queue q;
        vector dist(n+1, -1);
        q.push(0);
        dist[0]=0;
        while (q.size()){
            int t = q.front();
            q.pop();
            if(t==n) return dist[t];
            for(int i = 1; i*i+t<=n; i++){
                int j = t+i*i;
                if(dist[j] == -1){
                    dist[j] = dist[t] + 1;
                    q.push(j);
                }
            }
        }
        return 0;
    }
};

LeetCode 306 累加数

class Solution {
public:
    bool isAdditiveNumber(string num) {
        for(int i = 1; i < num.size(); i++){
            
             string s1 = num.substr(0, i);
            if(s1.size() > 1 && s1[0] == '0') break;
            for(int j = i + 1; j < num.size(); j++){
                 string s2 = num.substr(i, j-i);
            long d1 = stol(s1), d2 = stol(s2);
            if(s2.size()>1&&s2[0] == '0') break;
            long next = d1 + d2;
            string nextStr = to_string(next);
            if(nextStr!=num.substr(j, nextStr.length())) continue;
            string allStr = s1 + s2 + nextStr;
            while(allStr.size() < num.size()){
                d1 = d2;
                d2 = next;
                next = d1+d2;
                nextStr = to_string(next);
                allStr += nextStr;
            }
                if(allStr == num) return true;
            }     
        }
         return false;
            
    }
};

路径总和3

class Solution {
public:
    int pathSum(TreeNode* root, int sum) {
        int res = 0;
        vector path;
        dfs(root, sum, 0, path, res);
        return res; 
    }
    void dfs(TreeNode* root, int sum, int curSum, vector& path, int& res){
        if(!root) return;
        curSum += root->val;
        path.push_back(root);
        if(curSum == sum) ++res;
        int t = curSum;
        
        for(int i = 0; i < path.size()-1; i++){
            t -= path[i]->val;
            if(t == sum) ++res;
        }
        dfs(root->left, sum, curSum, path, res);
        dfs(root->right, sum, curSum, path, res);
        path.pop_back();
    }
};

LeetCode 363 矩形区域不超过 K 的最大数值和

code1(TLE)

class Solution {
public:
    int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {
        int n = matrix.size(), m = matrix[0].size();
        int res = INT_MIN;
        vector<vector<int>> f(n+1, vector<int>(m+1));
        for(int i = 1; i <= n; i++)
            for(int j = 1; j <= m; j++){
               f[i][j] = f[i-1][j]+f[i][j-1]-f[i-1][j-1] + matrix[i-1][j-1];
                //cout << "f["<
            }
        for(int x2 = 1; x2 <= n; x2++)
            for(int y2 = 1; y2 <= m; y2++)
                for(int x1 = 1; x1 <= x2; x1++)
                    for(int y1 = 1; y1 <= y2; y1++){
                        int temp; 
                        temp = f[x2][y2] - f[x1 - 1][y2] - f[x2][y1 - 1] + f[x1 - 1][y1 - 1];
                        //cout << "temp:"<
                        if(temp <= k) res = max(res, temp);
                    }
        return res;
    }
};

code2

class Solution {
public:
    int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {
        int row = matrix.size();
        if(!row) return 0;
        int col = matrix[0].size();
        if(!col) return 0;
        int ret = INT_MIN;

        for(int i=0; i<col; ++i) {
            vector<int> sum(row, 0);
            for(int j=i; j<col; ++j) {
                for(int r=0; r<row; ++r) sum[r] += matrix[r][j];
                int curSum = 0, curMax = INT_MIN;
                set<int> sumSet;
                sumSet.insert(0);
                for(int r=0; r<row; ++r) {
                    curSum += sum[r];
                    auto it = sumSet.lower_bound(curSum-k);
                    if(it != sumSet.end()) curMax = max(curMax, curSum-*it);
                    sumSet.insert(curSum);
                }
                ret = max(ret, curMax);
            }
        }
        return ret;
    }
};

code3

class Solution {
public:
int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {
    if (matrix.empty() || matrix[0].empty()) return 0;
     
    const int m = matrix.size(), n = matrix[0].size();
    int res = INT_MIN;
     
    for (int row1=0; row1<m; ++row1){
        vector<int> sum(n, 0);
        for (int row2=row1; row2<m; ++row2){
            for (int col=0; col<n; ++col){
                sum[col] += matrix[row2][col];
                if (sum[col] == k) return k;
            }
             
            int curr_sum = 0, curr_max = INT_MIN;
            for (int temp_s : sum){
                curr_sum += temp_s;
                if (curr_sum == k) return k;
                if (curr_sum < k && curr_sum > res) res = curr_sum;
                if (curr_sum < 0) curr_sum = 0;
            }
             
            if (curr_sum < k) continue;
            curr_sum = 0;
            set<int> sum_set{0};
            for (int temp_s : sum){
                curr_sum += temp_s;
                auto it = sum_set.lower_bound(curr_sum - k);
                 
                if (it != sum_set.end()){
                    if (*it == curr_sum - k) return k;
                    if (curr_sum - *it > res)
                        res = curr_sum - *it;
                }
                sum_set.insert(curr_sum);                   
            }
        }
    }
    return res;
}
};

LeetCode 382 链表随机节点

class Solution {
public:
    Solution(ListNode* head) {
        this->head = head;
    }
    int getRandom() {
        int res = head->val, i = 2;
        ListNode *cur = head->next;
        while (cur) {
            int j = rand() % i;
            if (j == 0) res = cur->val;
            ++i;
            cur = cur->next;
        }
        return res;
    }
private:
    ListNode *head;
};

水塘抽样:
算法岗面试准备LeetCode刷题专栏_第2张图片

LeetCode 415 字符串相加

class Solution {
public:
    string addStrings(string num1, string num2) {
        string res = "";
        int carry = 0;
        int m = num1.size(), n = num2.size();
        int i = m-1, j = n-1;
        while(i>=0||j>=0){
            int a = i>=0 ? num1[i--]-'0' : 0;
            int b = j>=0 ? num2[j--]-'0' : 0;
            int sum = a + b + carry;
            res.insert(res.begin(), sum % 10 + '0');
            carry = sum/10;
        }
        return carry ? '1'+res : res;
    }
};

LeetCode 416 分割等和子集

解法一

class Solution {
public:
    bool canPartition(vector& nums) {
        int sum = accumulate(nums.begin(), nums.end(), 0);
        const int N = nums.size();
        int target = sum >> 1;
        if (sum % 2 != 0) return false;
        //dp[i][j] means whether we can sum to j using first i numbers.
        vector> dp(N + 1, vector(sum + 1, false));
        // every number can build number 0.
        for (int i = 0; i <= N; ++i) {
            dp[i][0] = true;
        }
        // but for position 0, it can build number nothing.
        for (int j = 1; j <= target; ++j) {
            dp[0][j] = false;
        }
        // anyway, position 0 can build number 0.
        dp[0][0] = true;
        for (int i = 1; i <= N; ++i) {
            for (int j = 0; j <= target; ++j) {
                if (j >= nums[i - 1])
                    dp[i][j] = dp[i - 1][j] || dp[i - 1][j - nums[i - 1]];
                else
                    dp[i][j] = dp[i - 1][j];
            }
        }
        return dp[N][target];
    }
};

解法二

class Solution {
public:
    bool canPartition(vector& nums) {
        int sum = accumulate(nums.begin(), nums.end(), 0), target = sum >> 1;
        if(sum & 1) return false;
        vector dp(target+1, false);
        dp[0] = true;
        for(int num:nums){
            for(int i = target; i >= num; i--){
                dp[i] = dp[i]||dp[i-num];
            }

        }
    return dp[target];
    }
};

LeetCode 443 压缩字符串

class Solution {
public:
int compress(vector<char>& chars){
    int n = chars.size();
    int count = 1;
    vector<char> res;
    res.push_back(chars[0]);
    for(int i = 1; i < n; i++){
        if(chars[i] == chars[i-1]){
            count++;
            continue;
        }
        if(count != 1){
           if(count/10) res.push_back(count/10+'0');
            res.push_back(count%10+'0');
        }
        res.push_back(chars[i]); 
        count = 1;
    }
    if(count != 1) {
        if(count/10) res.push_back(count/10+'0');
        res.push_back(count%10+'0');
    }
    for(int i = 0; i < res.size(); i++){
        chars[i] = res[i];
    }   
    return res.size();
}
};

LeetCode 445 两数相加 II

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        stack s1, s2;
        while(l1){
            s1.push(l1->val);
            l1 = l1->next;
        }
        while(l2){
            s2.push(l2->val);
            l2 = l2->next;
        }
        int sum = 0;
        ListNode* res = new ListNode(0);
        while(!s1.empty()||!s2.empty()){
            if(!s1.empty()) {sum += s1.top(); s1.pop();}
            if(!s2.empty()) {sum += s2.top(); s2.pop();}
            res->val = sum % 10;
            ListNode* head = new ListNode(sum/10);
            head->next = res;
            res = head;
            sum /= 10;
        }
        return res->val == 0 ? res->next:res;
    }
};

LeetCode 456 132模式

class Solution {
public:
    bool find132pattern(vector& nums) {
        int n = nums.size(), mn = INT_MAX;
        for(int j = 0; j < n; j++){
            mn = min(mn, nums[j]);
            if(mn == nums[j]) continue;
            for(int k = n-1; k >= j; k--){
                 if(mn < nums[k] && nums[j] > nums[k]) return true;       
            }
        } 
        return false;
    }
};

LeetCode 474 一和零

class Solution {
public:
    int findMaxForm(vector& strs, int m, int n) {
        vector> dp(m+1, vector(n+1, 0));
        for(string str : strs){
            int zeros = 0, ones = 0;
            for(char c : str)(c == '0') ? ++zeros : ++ones;
            for(int i = m; i >= zeros; i--){
                for(int j = n; j >= ones; j--){
                    dp[i][j] = max(dp[i][j], dp[i-zeros][j-ones]+1);
                }
            }
        }
        return dp[m][n];
    }
};

LeetCode 509 斐波那契数

class Solution {
public:
    int fib(int N) {
        if(N==0)
           return 0; 
        if(N==1)
           return 1;
        return fib(N-1)+fib(N-2);
    }
};

LeetCode 543 二叉树的直径(DFS)

class Solution {
public:
    int diameterOfBinaryTree(TreeNode* root) {
     int ans = 0;
     dfs(root, ans);
     return ans;
    }
    int dfs(TreeNode *r, int &ans){
        if(r == NULL) return -1;
        int d1 = dfs(r->left, ans);
        int d2 = dfs(r->right, ans);
        ans = max(ans, d1+d2+2);
        return max(d1, d2)+1;
    }
};

LeetCode 707 设计链表

class MyLinkedList {
public:
    MyLinkedList() {
        head = NULL;
        size = 0;
    }
    int get(int index) {
        if (index < 0 || index >= size) return -1;
        Node *cur = head;
        for (int i = 0; i < index; ++i) cur = cur->next;
        return cur->val;
    }
    void addAtHead(int val) {
        Node *t = new Node(val, head);
        head = t;
        ++size;
    }
    void addAtTail(int val) {
        Node *cur = head;
        while (cur->next) cur = cur->next;
        cur->next = new Node(val, NULL);
        ++size;
    }
    void addAtIndex(int index, int val) {
        if (index > size) return;
        if (index <= 0) {addAtHead(val); return;}
        Node *cur = head;
        for (int i = 0; i < index - 1; ++i) cur = cur->next;
        Node *t = new Node(val, cur->next);
        cur->next = t;
        ++size;
    }
    void deleteAtIndex(int index) {
        if (index < 0 || index >= size) return;
        if (index == 0) {
            head = head->next;
            --size;
            return;
        }
        Node *cur = head;
        for (int i = 0; i < index - 1; ++i) cur = cur->next;
        cur->next = cur->next->next;
        --size;
    }
    
private:
    struct Node {
        int val;
        Node *next;
        Node(int x, Node* n): val(x), next(n) {}
    };
    Node *head, *tail;
    int size;
};

LeetCode 718 最长重复子数组

class Solution {
public:
    int findLength(vector& A, vector& B) {
        int m = A.size(), n = B.size();
        int dp[m][n];
        int res = 0;
        for(int i = 0; i < m; i++) dp[i][0] = A[i] == B[0] ? 1 : 0;
        for(int j = 0; j < n; j++) dp[0][j] = A[0] == B[j] ? 1 : 0;
        for(int i = 1; i < m; i++){
            for(int j = 1; j < n; j++){
                dp[i][j] = A[i] == B[j] ? dp[i-1][j-1] + 1 : 0;
                res = max(res, dp[i][j]);
            }   
        }
         return res;  
    }
};

LeetCode 733 图像渲染

class Solution {
public:
    vector> floodFill(vector>& image, int sr, int sc, int newColor) {
        if(image.empty()||image[0].empty()) return image;
        int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
        int oldColor = image[sr][sc];
        if(oldColor == newColor) return image;
        image[sr][sc] = newColor;
        for(int i = 0; i<4; i++ ){
            int x = sr + dx[i], y = sc + dy[i];
            if(x >= 0 && x < image.size() && y >= 0 && y < image[0].size() && image[x][y] == oldColor)
                floodFill(image, x, y, newColor);
        }
        return image;
    }
};

LeetCode 784 字母大小写全排列

class Solution {
public:
    vector ans;
    vector letterCasePermutation(string S) {
        dfs(S, 0);
        return ans;
    }
    void dfs(string S, int t){
        if(t==S.size()) {
            ans.push_back(S); 
            return;   
        }  
        dfs(S, t+1);
        if(S[t]>='A'){
            S[t]^=32;
            dfs(S, t+1);
        }
    }
};

LeetCode 921 使括号有效的最少添加

#include
#include

using namespace std;

class Solution {
public:
	int minAddToMakeValid(string S) {
		int len = S.length();
		int first = 0, last = 0; //first记录反括号数量,last记录括号数量
		for (int i = 0; i < len; i++) {
			if (S[i] == '(')last++;
			else {
				if (last == 0)first++;
				else last--;
			}
		}
		return first + last;
	}
};

int main() {
	string S = "(((";
	int result = Solution().minAddToMakeValid(S);
	cout << result << endl;
	system("pause");
}

LeetCode 1074 元素和为目标值的子矩阵数量

class Solution {
public:
    int numSubmatrixSumTarget(vector>& matrix, int target) {
        int n = matrix.size(), m = matrix[0].size();
        int ans = 0;

        for (int i = 0; i < n; i++)
            for (int j = 1; j < m; j++)
                matrix[i][j] += matrix[i][j - 1];

        for (int l = 0; l < m; l++)
            for (int r = l; r < m; r++) {
                unordered_map vis;
                vis[0] = 1;
                int tot = 0;
                for (int k = 0; k < n; k++) {
                    if (l == 0) {
                        tot += matrix[k][r];
                    } else {
                        tot += matrix[k][r] - matrix[k][l - 1];
                    }
                    if (vis.find(tot - target) != vis.end())
                        ans += vis[tot - target];
                    vis[tot]++;
                }
            }
        return ans;
    }
};

LeetCode 1389 按既定顺序创建目标数组

class Solution {
public:
    vector<int> createTargetArray(vector<int>& nums, vector<int>& index) {
        int n = nums.size();
        vector<int> target(n);
        int trail = -1;
        for(int i = 0; i < n; i++){
            trail++;
            for(int j = trail; j>index[i]; j--){
                target[j] = target[j-1];
            }
            target[index[i]]=nums[i];
        }
        return target;
    }
};

LeetCode 1390 四因数

class Solution {
public:
    int sumFourDivisors(vector<int>& nums) {
        int n = nums.size();
        int ans = 0;
        for(int i = 0; i < n; i++){
            int k = nums[i];
            int cnt = 0;
            int sum = 0;
            for(int j = 1; j <= sqrt(k); j++){
                if(k%j == 0) {
                    sum += j, cnt++;
                    if(k/j != j) sum += k/j, cnt++;
                }
            }
            if(cnt == 4) ans += sum;
        }
        return ans;
    }
};

你可能感兴趣的:(算法笔试,C++,算法与数据结构)