1.从双倍数组中还原原数组(力扣,vector)
java式c++解法。
class Solution {
public:
vector<int> findOriginalArray(vector<int>& changed) {
int n = changed.size();
if(n % 2 == 1) return {};
map<int, int> mp;
for(int c : changed) mp[c]++;
sort(changed.begin(), changed.end());
vector<int> ans;
int i = 0;
while(i < n){
int x = changed[i];
if(mp[x] > 0){
mp[x]--;
if(mp[x * 2] <= 0) return {};
mp[x * 2]--;
ans.push_back(x);
}
i++;
}
return ans;
}
};
2.组合总和|||(力扣,vector,二维数组,dfs)
vector,dfs。
class Solution {
public:
vector<vector<int>> v;
vector<int> tmp;
void dfs(int u,int sum,int ct){
if(sum<0) return ;
if(sum==0&&ct==0){
v.push_back(tmp);
return ;
}
if(u>9||ct<=0) return;
tmp.push_back(u);
dfs(u+1,sum-u,ct-1);
tmp.pop_back();
dfs(u+1,sum,ct);
}
vector<vector<int>> combinationSum3(int k, int n) {
dfs(1,n,k);
return v;
}
};
3.组和总和(力扣,一维背包动态规划)
动态规划
class Solution {
public int combinationSum4(int[] nums, int target) {
int[] dp = new int[target + 1];
dp[0] = 1;
for (int i = 1; i <= target; i++) {
for (int num : nums) {
if (num <= i) {
dp[i] += dp[i - num];
}
}
}
return dp[target];
}
}
作者:力扣官方题解
链接:https://leetcode.cn/problems/combination-sum-iv/solutions/740581/zu-he-zong-he-iv-by-leetcode-solution-q8zv/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
4.给植物浇水1
class Solution {
public:
int wateringPlants(vector<int>& plants, int capacity) {
int n = plants.size();
int ans = 0;
int rest = capacity;
for (int i = 0; i < n; ++i) {
if (rest >= plants[i]) {
++ans;
rest -= plants[i];
}
else {
ans += i * 2 + 1;
rest = capacity - plants[i];
}
}
return ans;
}
};
5.给植物浇水2
int minimumRefill(int* plants, int plantsSize, int capacityA, int capacityB) {
int res = 0; // 灌满水罐次数
int n = plantsSize;
int posa = 0, posb = n - 1; // 两人位置
int vala = capacityA, valb = capacityB; // 两人剩余水量
// 模拟相遇前的浇水过程
while (posa < posb) {
if (vala < plants[posa]) {
++res;
vala = capacityA - plants[posa];
} else {
vala -= plants[posa];
}
++posa;
if (valb < plants[posb]) {
++res;
valb = capacityB - plants[posb];
} else {
valb -= plants[posb];
}
--posb;
}
// 模拟相遇后可能的浇水过程
if (posa == posb) {
if (vala >= valb && vala < plants[posa]) {
++res;
}
if (vala < valb && valb < plants[posb]) {
++res;
}
}
return res;
}