leetcode算法题--使子序列的和等于目标的最少操作次数

原题链接:https://leetcode.cn/problems/minimum-operations-to-form-subsequence-with-target-sum/description/

视频讲解:https://www.bilibili.com/video/BV1Em4y1T7Bq?t=1456.1

这题是真的难。。

go 复制代码
func minOperations(nums []int, target int) int {
    s:= 0
    cnt := [31]int{}
    for _, num := range nums {
        s += num
        cnt[bits.TrailingZeros(uint(num))]++
    }
    if s < target {
        return -1
    }
    if s == target {
        return 0
    }
    s = 0 
    ans := 0 
    i := 0
    for 1 << i <= target {
        s += cnt[i] << i // cnt[i] * (1 << i) 
        mask := 1<<(i+1) - 1
        if s >= target&mask {
            // if s >= target&mask > (2 ^ i)
            // 可以由小于target&mask的数合成
            i++ 
            continue
        }
        ans++
        // 比如从32(2^5)分到8(2^3), 32 -> 16 -> 8, 需要5-3=2次 
        for i++; cnt[i] == 0; i++ {
            ans++
        }
    }
    return ans  
}
相关推荐
CoovallyAIHub1 小时前
181小时视频丢给GPT-5,准确率只有15%——南大联合NVIDIA等五校发布多模态终身理解数据集
深度学习·算法·计算机视觉
CoovallyAIHub1 小时前
CVPR 2026 | GS-CLIP:3D几何先验+双流视觉融合,零样本工业缺陷检测新SOTA,四大3D工业数据集全面领先!
深度学习·算法·计算机视觉
xlp666hub2 小时前
Leetcode 第三题:用C++解决最长连续序列
c++·leetcode
有意义4 小时前
深度拆解分割等和子集:一维DP数组与倒序遍历的本质
前端·算法·面试
xlp666hub5 小时前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode
用户726876103375 小时前
解放双手的健身助手:基于 Rokid AR 眼镜的运动计时应用
算法
Wect5 小时前
LeetCode 17. 电话号码的字母组合:回溯算法入门实战
前端·算法·typescript
xlp666hub1 天前
Leetcode第一题:用C++解决两数之和问题
c++·leetcode
ZhengEnCi1 天前
08c. 检索算法与策略-混合检索
后端·python·算法
程序员小崔日记1 天前
大三备战考研 + 找实习:我整理了 20 道必会的时间复杂度题(建议收藏)
算法·408·计算机考研