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  
}
相关推荐
6Hzlia4 分钟前
【Hot 100 刷题计划】 LeetCode 78. 子集 | C++ 回溯算法题解
c++·算法·leetcode
Kethy__7 分钟前
计算机中级-数据库系统工程师-数据结构-查找算法
数据结构·算法·软考·查找算法·计算机中级
所以遗憾是什么呢?11 分钟前
【题解】Codeforces Round 1081 (Div. 2)
数据结构·c++·算法·acm·icpc·ccpc·xcpc
xiaoye-duck1 小时前
《算法题讲解指南:递归,搜索与回溯算法--综合练习》--14.找出所有子集的异或总和再求和,15.全排列Ⅱ,16.电话号码的字母组合,17.括号生成
c++·算法·深度优先·回溯
OOJO1 小时前
c++---vector介绍
c语言·开发语言·数据结构·c++·算法·vim·visual studio
汀、人工智能1 小时前
05 - 函数基础
数据结构·算法·数据库架构·05 - 函数基础
HAPPY酷2 小时前
Python高级架构师之路——从原理到实战
java·python·算法
枫叶林FYL2 小时前
第9章 因果推理与物理理解
人工智能·算法·机器学习
小白zlm2 小时前
预畸变双线性变换
单片机·嵌入式硬件·算法·电机控制
wuweijianlove3 小时前
算法复杂度估算的实验建模与可视化表达的技术6
算法