for dfs|二分
lc1513
组合数学
typedef long long ll;
class Solution {
/*
输入:s = "0110111"
输出:9
*/
int mod=1e9+7;
public:
int numSub(string s)
{
int n=s.size(),i=0;
ll ret=0;
while(i<n)
{
while(i<n && s[i]=='0')
i++;
int cnt=0;
while(i<n && s[i]=='1')
{
cnt++;
i++;
}
ret=(ret+(ll)cnt*(cnt+1)/2)%mod;
}
return (int)ret;
}
};
lc2187
问题问什么,就二分什么的
二分查找快速找到完成指定总行程(totalTrips)的最短时间:
以“时间x能否完成目标行程”为判断条件
class Solution {
public:
long long minimumTime(vector<int>& time, int totalTrips) {
auto check = [&](long long x) -> bool {
long long sum = 0;
for (int t : time) {
sum += x / t;
//loop time +every bus 可走次数
if (sum >= totalTrips)
return true;
}
return false;
};
int min_t = ranges::min(time);
long long left = min_t;
long long right = 1LL * min_t * totalTrips; // 循环不变量:check(right) 恒为 true
while (left <= right)
{
long long mid = left + (right - left) / 2;
if(check(mid))
right=mid-1;
else
left=mid+1;
}
return left;
}
};
py3魅力时刻
class Solution:
def minimumTime(self, time: List[int], totalTrips: int) -> int:
check = lambda x: sum(x // t for t in time) >= totalTrips
min_t = min(time)
# bisect_left 需要用左闭右开区间
left = min_t
right = min_t * totalTrips
return bisect_left(range(right), True, left, key=check)
lc1855
单调_贪心
class Solution {
public:
int maxDistance(vector<int>& nums1, vector<int>& nums2)
{
int m=nums1.size(),n=nums2.size();
int j=0,mx=0;
for(int i=0;i<m;i++)
{
while(j<n && nums1[i]<=nums2[j])
j++;
mx=max(mx,j-i-1);
}
return mx;
}
};
lc1508
生成子数组
for(int i=0;i<n;i++)
dfs(i,0);
class Solution {
vector<int> t;
vector<int> nums;
int n;
int mod=1e9+7;
public:
int rangeSum(vector<int>& nums, int n, int left, int right)
{
this->n=n;
this->nums=nums;
for(int i=0;i<n;i++)
dfs(i,0);
sort(t.begin(),t.end());
int ret=0;
for(int i=left-1;i<right;i++)
{
ret=(ret+t[i])%mod;
}
return ret;
}
void dfs(int p,int sum)
{
if(p==n)
return;
sum+=nums[p];
t.push_back(sum);
dfs(p+1,sum);
}
};
