目标和
分析:
dfs不断尝试,然后回溯。
代码:
class Solution {
public:
int cnt = 0;
void dfs(vector<int>& nums, int target, int ind, int sum) {
if(ind == nums.size()) {
if(sum == target) {
cnt++;
}
return;
}
dfs(nums, target, ind + 1, sum + nums[ind]);
dfs(nums, target, ind + 1, sum - nums[ind]);
}
int findTargetSumWays(vector<int>& nums, int target) {
dfs(nums, target, 0, 0);
return cnt;
}
};
把二叉搜索树转换为累加树
分析:
BST的中序遍历是升序的,而反中序遍历是降序的。因此,在反中序遍历过程中,不断累加当前值,就能得到满足条件的新值。
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int sum = 0;
TreeNode* convertBST(TreeNode* root) {
if(root) {
convertBST(root->right);
// cout << root->val << " ";
sum += root->val;
root->val = sum;
convertBST(root->left);
}
return root;
}
};
最短无序连续子数组
方法一:
暴力求解:枚举左右边界,排序后再判断整体是否有序,最后超时。
代码:
class Solution {
public:
int findUnsortedSubarray(vector<int>& nums) {
int n = nums.size();
vector<int> re = nums;
int res = INT_MAX;
for(int left = 0; left < n; left++) {
for(int right = left; right <= n; right++) {
sort(nums.begin() + left, nums.begin() + right);
if(is_sorted(nums.begin(), nums.end())) {
res = min(res, right - left);
}
nums = re;
}
}
return res;
}
};
方法二:
将一个数组分为左中右三个部分,我们需要寻找一个最短的中间部分使其排序后整体也有序。因此可以先将数组排序,再与原数组比较,找到两个数组中不同部分的长度。
代码:
class Solution {
public:
int findUnsortedSubarray(vector<int>& nums) {
if(is_sorted(nums.begin(), nums.end())) {
return 0;
}
int n = nums.size();
vector<int> copy(nums);
sort(nums.begin(), nums.end());
int left = 0, right = n - 1;
while(left < n && nums[left] == copy[left]) {
left++;
}
while(right >= 0 && nums[right] == copy[right]) {
right--;
}
return right - left + 1;
}
};