1. 数组的连续子序列最大和

题目
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.

方法一:分治法O(nlogn)

因为最大子序列和可能在三处出现,整个出现在数组左半部,或者整个出现在右半部,又或者跨越中间,占据左右两半部分。递归将左右子数组再分别分成两个数组,直到子数组中只含有一个元素,退出每层递归前,返回上面三种情况中的最大值。

  1. #include<limits.h>
  2. int Max3(int a,int b,int c)
  3. {
  4. int Max = a;
  5. if(b > Max)
  6. Max = b;
  7. if(c > Max)
  8. Max = c;
  9. return Max;
  10. }
  11. int MaxSubSum2(int *arr,int left,int right)
  12. {
  13. int MaxLeftSum,MaxRightSum; //左右边的最大和
  14. int MaxLeftBorderSum,MaxRightBorderSum; //含中间边界的左右部分最大和
  15. int LeftBorderSum,RightBorderSum; //含中间边界的左右部分当前和
  16. int i,center;
  17. //递归到最后的基本情况
  18. if(left == right)
  19. //(X)if(arr[left]>0)
  20. return arr[left];
  21. //(X)else
  22. //(X) return 0;
  23. //求含中间边界的左右部分的最大值
  24. center = (left + right)/2;
  25. MaxLeftBorderSum = INT_MIN;
  26. LeftBorderSum = 0;
  27. for(i=center;i>=left;i--)
  28. {
  29. LeftBorderSum += arr[i];
  30. if(LeftBorderSum > MaxLeftBorderSum)
  31. MaxLeftBorderSum = LeftBorderSum;
  32. }
  33. MaxRightBorderSum = INT_MIN;
  34. RightBorderSum = 0;
  35. for(i=center+1;i<=right;i++)
  36. {
  37. RightBorderSum += arr[i];
  38. if(RightBorderSum > MaxRightBorderSum)
  39. MaxRightBorderSum = RightBorderSum;
  40. }
  41. //递归求左右部分最大值
  42. MaxLeftSum = MaxSubSum2(arr,left,center);
  43. MaxRightSum = MaxSubSum2(arr,center+1,right);
  44. //返回三者中的最大值
  45. return Max3(MaxLeftSum,MaxRightSum,MaxLeftBorderSum+MaxRightBorderSum);
  46. }
  47. /*
  48. 将分支策略实现的算法封装起来
  49. */
  50. int MaxSubSum2_1(int *arr,int len)
  51. {
  52. return MaxSubSum2(arr,0,len-1);
  53. }

方法二:神奇的方法O(n)

连续子序列最大和的特征:若A[i]+A[j]< 0则i,j必不在 最大连续子序列 的 序列中。

  1. #include<limits.h>
  2. class Solution {
  3. public:
  4. int maxSubArray(vector<int>& nums)
  5. {
  6. int i,len;
  7. int MaxSum = INT_MIN; //防止数组全是小于零的数
  8. int ThisSum= 0;
  9. len = nums.size();
  10. for(i=0;i<len;i++)
  11. {
  12. ThisSum+= nums[i];
  13. if(ThisSum > MaxSum)
  14. MaxSum = ThisSum;
  15. if(ThisSum< 0)
  16. ThisSum= 0;
  17. }
  18. return MaxSum;
  19. }
  20. };

2. 二叉树中的最大“路径”和

题目:
路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。路径和 是路径中各节点值的总和。
给你一个二叉树的根节点 root ,返回其 最大路径和

示例 :

递归&分治法 - 图1
输入:root = [-10,9,20,null,null,15,7]
输出:42
解释:最优路径是 15 -> 20 -> 7 ,路径和为 15 + 20 + 7 = 42

  1. class Solution {
  2. private:
  3. int maxSum = INT_MIN;
  4. public:
  5. int maxGain(TreeNode* node) {
  6. if (node == nullptr) {
  7. return 0;
  8. }
  9. // 递归计算左右子节点的最大贡献值
  10. // 只有在最大贡献值大于 0 时,才会选取对应子节点
  11. int leftGain = max(maxGain(node->left), 0);
  12. int rightGain = max(maxGain(node->right), 0);
  13. // 节点的最大路径和取决于该节点的值与该节点的左右子节点的最大贡献值
  14. int priceNewpath = node->val + leftGain + rightGain;
  15. // 更新答案
  16. maxSum = max(maxSum, priceNewpath);
  17. // 返回节点的最大贡献值
  18. return node->val + max(leftGain, rightGain);
  19. }
  20. int maxPathSum(TreeNode* root) {
  21. maxGain(root);
  22. return maxSum;
  23. }
  24. };

3. 字符串解码

给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。
你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。

示例 1:
输入:s = “3[a]2[bc]”
输出:”aaabcbc”

示例 2:
输入:s = “3[a2[c]]”
输出:”accaccacc”

  1. class Solution {
  2. public:
  3. string src;
  4. size_t ptr;
  5. int getDigits() {
  6. int ret = 0;
  7. while (ptr < src.size() && isdigit(src[ptr])) {
  8. ret = ret * 10 + src[ptr++] - '0';
  9. }
  10. return ret;
  11. }
  12. string getString() {
  13. if (ptr == src.size() || src[ptr] == ']') {
  14. // String -> EPS
  15. return "";
  16. }
  17. char cur = src[ptr]; int repTime = 1;
  18. string ret;
  19. if (isdigit(cur)) {
  20. // String -> Digits [ String ] String
  21. // 解析 Digits
  22. repTime = getDigits();
  23. // 过滤左括号
  24. ++ptr;
  25. // 解析 String
  26. string str = getString();
  27. // 过滤右括号
  28. ++ptr;
  29. // 构造字符串
  30. while (repTime--) ret += str;
  31. } else if (isalpha(cur)) {
  32. // String -> Char String
  33. // 解析 Char
  34. ret = string(1, src[ptr++]);
  35. }
  36. return ret + getString();
  37. }
  38. string decodeString(string s) {
  39. src = s;
  40. ptr = 0;
  41. return getString();
  42. }
  43. };

4. 二叉树的最近公共祖先

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

示例 1:
递归&分治法 - 图2
输入:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
输出:3

解释:节点 5 和节点 1 的最近公共祖先是节点 3 。

  1. 官解:
  2. class Solution {
  3. public:
  4. TreeNode* ans;
  5. bool dfs(TreeNode* root, TreeNode* p, TreeNode* q) {
  6. if (root == nullptr) return false;
  7. bool lson = dfs(root->left, p, q);
  8. bool rson = dfs(root->right, p, q);
  9. if ((lson && rson) || ((root->val == p->val || root->val == q->val) && (lson || rson))) {
  10. ans = root;
  11. }
  12. return lson || rson || (root->val == p->val || root->val == q->val);
  13. }
  14. TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
  15. dfs(root, p, q);
  16. return ans;
  17. }
  18. };
  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. // mysolution
  11. class Solution {
  12. private:
  13. TreeNode* ancestor=NULL;
  14. public:
  15. TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
  16. bool ifp=false,ifq=false;
  17. recursion(root,ifp,ifq,p,q);
  18. return ancestor;
  19. }
  20. bool recursion(TreeNode *root, bool &ifp,bool &ifq,TreeNode* p, TreeNode* q){
  21. if(!root) return false;
  22. bool find1,find2;
  23. bool bp1 =false,bq1 =false;
  24. find1 = recursion(root->left,bp1,bq1,p,q);
  25. if(find1) return true;
  26. bool bp2 =false,bq2 =false;
  27. find2 = recursion(root->right,bp2,bq2,p,q);
  28. if(find2) return true;
  29. if(root->val == p->val){
  30. ifp = true;
  31. ifq = (bq1||bq2);
  32. }
  33. else if(root->val == q->val){
  34. ifq = true;
  35. ifp = (bp1||bp2);
  36. }else{
  37. ifp = (bp1||bp2);
  38. ifq = (bq1||bq2);
  39. }
  40. if(ifp && ifq && !ancestor){
  41. ancestor = root;
  42. return true;
  43. }
  44. return false;
  45. }
  46. };

5. 分支界限——大礼包

在LeetCode商店中, 有许多在售的物品。
然而,也有一些大礼包,每个大礼包以优惠的价格捆绑销售一组物品。
现给定每个物品的价格,每个大礼包包含物品的清单,以及待购物品清单。请输出确切完成待购清单的最低花费。
每个大礼包的由一个数组中的一组数据描述,最后一个数字代表大礼包的价格,其他数字分别表示内含的其他种类物品的数量。
任意大礼包可无限次购买。

示例 1:
输入: [2,5], [[3,0,5],[1,2,10]], [3,2]
输出: 14
解释:
有A和B两种物品,价格分别为¥2和¥5。
大礼包1,你可以以¥5的价格购买3A和0B。
大礼包2, 你可以以¥10的价格购买1A和2B。
你需要购买3个A和2个B, 所以你付了¥10购买了1A和2B(大礼包2),以及¥4购买2A。

示例 2:
输入: [2,3,4], [[1,1,0,4],[2,2,1,9]], [1,2,1]
输出: 11
解释:
A,B,C的价格分别为¥2,¥3,¥4.
你可以用¥4购买1A和1B,也可以用¥9购买2A,2B和1C。
你需要买1A,2B和1C,所以你付了¥4买了1A和1B(大礼包1),以及¥3购买1B, ¥4购买1C。
你不可以购买超出待购清单的物品,尽管购买大礼包2更加便宜。
说明:
最多6种物品, 100种大礼包。
每种物品,你最多只需要购买6个。
你不可以购买超出待购清单的物品,即使更便宜。

  1. class Solution
  2. {
  3. private:
  4. map<vector<int>, int> records;
  5. public:
  6. int shoppingOffers(vector<int>& price, vector<vector<int>>& special, vector<int>& needs) {
  7. if(records.find(needs)!=records.end())
  8. return records[needs];
  9. int res=0,n=needs.size();
  10. for (int i = 0; i < n;i++)
  11. {
  12. res += needs[i] *price[i];
  13. }
  14. for (auto gift: special){
  15. vector<int> copyneeds(needs);
  16. int i;
  17. for (i = 0; i < n;i++){
  18. if(gift[i] > needs[i]){
  19. break;
  20. }
  21. else{
  22. copyneeds[i] -= gift[i];
  23. }
  24. }
  25. if(i==n){
  26. res = min(res, gift[i] + shoppingOffers(price, special, copyneeds));
  27. }
  28. }
  29. records[needs] = res;
  30. return res;
  31. }
  32. };

6.为表达式设计优先级

题目:
给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及
示例:
输入: “2
3-45”
输出: [-34, -14, -10, -10, 10]
解释:
(2
(3-(45))) = -34
((2
3)-(45)) = -14
((2
(3-4))5) = -10
(2
((3-4)5)) = -10
(((2
3)-4)5) = 10
算法:
每一个表达式都可以写成 exp = exp1 op exp2 的形式,因此可用递归求解
此外可用*备忘录优化
,记录已经算出所有结果的表达式。

  1. class Solution {
  2. private:
  3. unordered_map<string, vector<int>> mymap;
  4. public:
  5. vector<int> diffWaysToCompute(string expression) {
  6. if(mymap.find(expression)!=mymap.end()){
  7. return mymap[expression];
  8. }
  9. int n=expression.size(),num=0,i;
  10. vector<int> res;
  11. for(i=0;i<n;i++){
  12. if(expression[i]<'0' || expression[i]>'9') break;
  13. num = num*10 + expression[i] - '0';
  14. }
  15. if(i==n){
  16. res.push_back(num);
  17. return res;
  18. }
  19. for(i=0;i<n;i++){
  20. if(expression[i]>='0' && expression[i]<='9') continue;
  21. vector<int> left = diffWaysToCompute(expression.substr(0, i));
  22. vector<int> right = diffWaysToCompute(expression.substr(i+1,n-1-i));
  23. for(auto x : left){
  24. for(auto y: right){
  25. switch(expression[i]){
  26. case '+':res.push_back(x+y);break;
  27. case '-':res.push_back(x-y);break;
  28. case '*':res.push_back(x*y);break;
  29. default:break;
  30. }
  31. }
  32. }
  33. }
  34. mymap[expression] = res;
  35. return res;
  36. }
  37. };