class Solution {
public:
const long long mod=1e9+7;
int countHomogenous(string s) {
long long ans=1;
int n=s.size();
long long cnt=1;
for(int i=1;i<n;i++)
{
if(s[i]==s[i-1])cnt++;
else cnt=1;
ans=(ans+cnt)%mod;
}
return (int)ans;
}
};
1755. 最接近目标值的子序列和
折半枚举+二分
题解: LeetCode 1755. 最接近目标值的子序列和
class Solution {
public:
int minAbsDifference(vector<int>& nums, int goal) {
int n=nums.size();
long long ans=abs(goal);
int m=n>>1;
vector<long long>v;
for(int i=0;i<(1<<m);i++)
{
long long sum=0;
for(int j=0;j<m;j++)
{
if(i&(1<<j))sum+=nums[j];
}
v.push_back(sum);
}
int cnt=v.size();
sort(v.begin(),v.end());
for(int i=0;i<(1<<(n-m));i++)
{
long long sum=0;
for(int j=0;j<n-m;j++)
{
if(i&(1<<j))sum+=nums[j+m];
}
int idx=lower_bound(v.begin(),v.end(),goal-sum)-v.begin();
if(idx>0)ans=min(ans,abs(sum+v[idx-1]-goal));
if(idx<cnt)ans=min(ans,abs(sum+v[idx]-goal));
}
return (int)ans;
}
};