首页 > 其他分享 >Leetcode(剑指offer专项训练)——DP专项(4)

Leetcode(剑指offer专项训练)——DP专项(4)

时间:2023-04-01 16:56:23浏览次数:57  
标签:专项 target nums int sum vector dp Leetcode DP

加减的目标值

给定一个正整数数组 nums 和一个整数 target 。
向数组中的每个整数前添加 '+' 或 '-' ,然后串联起所有整数,可以构造一个 表达式 :
例如,nums = [2, 1] ,可以在 2 之前添加 '+' ,在 1 之前添加 '-' ,然后串联起来得到表达式 "+2-1" 。
返回可以通过上述方法构造的、运算结果等于 target 的不同 表达式 的数目。
链接

WA:暴力题解

果然暴力就是超时

class Solution {
public:
    int findTargetSumWays(vector<int>& nums, int target) {
        int n=nums.size();
        vector<int>temp,t;
        for(int i=0;i<n;i++){
            if(i==0){
                temp.push_back(nums[i]);
                temp.push_back(-nums[i]);
            }else{
                for(auto num:temp){
                    t.push_back(num+nums[i]);
                    t.push_back(num-nums[i]);
                }
                temp=t;
                t.clear();
            }

        }
        int ans=0;
        for(auto num:temp){
            if(num==target){
                ans++;
            }
        }
        return ans;
    }
};

AC:DP题解

思路:sum来判断走到每一个nums下标的边界值[-sum,sum],然后计算走到当前的nums[i]需要几步

class Solution {
public:
    int findTargetSumWays(vector<int>& nums, int target) {
        int n=nums.size();
        vector<vector<int> >dp(n,vector<int>(40001,0));
        int add=20000;
        //初始化
        dp[0][add+nums[0]]=1;
        dp[0][add-nums[0]]++;//这里要注意如果nums[0]==0,则不可以用简单的赋值语句dp[0][add-nums[0]]=1
        //dp
        int sum=0;
        sum+=nums[0];
        for(int i=1;i<n;i++){
            sum+=nums[i];
            for(int j=-sum;j<=sum;j++){
               dp[i][j+add]=dp[i-1][j-nums[i]+add]+dp[i-1][j+nums[i]+add];
            }
        }
        
        return dp[n-1][target+add];
    }
};

官方题解

DFS

可能是因为nums的长度为20,所以时间复杂度\(O(2^n)\)可以接受
DFS解法如下:

class Solution {
public:
    int count = 0;
    int n;
    int t;
    void dfs(int index,int sum,vector<int>&nums){
        if(index<n){
            dfs(index+1,sum+nums[index],nums);
            dfs(index+1,sum-nums[index],nums);
        }else if(index==n&&sum==t){
            count++;
        }
    }
    int findTargetSumWays(vector<int>& nums, int target){
        n=nums.size();
        t=target;
        dfs(0,0,nums);
        return count;
    }
};

标签:专项,target,nums,int,sum,vector,dp,Leetcode,DP
From: https://www.cnblogs.com/SaltyCheese/p/17278885.html

相关文章

  • 代码随想录Day17-Leetcode110.平衡二叉树,257. 二叉树的所有路径,404.左叶子之和
    110.平衡二叉树题目链接:https://leetcode.cn/problems/balanced-binary-tree/一个显然但似乎不太高效的方法是:通过递归获取左右子树高度,判断差;然后递归判断左右结点;那么一个显然的改进就是后序遍历/***Definitionforabinarytreenode.*functionTreeNode(val......
  • 关于网络通信中TCP/UDP的端口范围-以及在Linux系统中的使用权限说明
    关于TCP/UDP的端口号的范围都是0~65535 根据IANA定义,可以参考如下链接:https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtmlIANA将这些端口分成了3类,LastUpdated2023-03-30Portnumbersareassignedinvariousways,based......
  • 调试freeradius时遇到的 线程池以及udp相关问题
    调试线程池过程中遇到了一个return和pthread_exit的问题;google一下发现右如下概念首先,return语句和pthread_exit()函数的含义不同,return的含义是返回,它不仅可以用于线程执行的函数,普通函数也可以使用;pthread_exit()函数的含义是线程退出,它专门用于结束某个线程的执行。在主......
  • leetcode876. 链表的中间结点
      876. 链表的中间结点方法一:最简单的做法,先求出整个链表的长度,再求1/2处节点的位置。/***Definitionforsingly-linkedlist.*structListNode{*intval;*ListNode*next;*ListNode():val(0),next(nullptr){}*ListNode(intx)......
  • leetcode-733-easy
    FloodFillAnimageisrepresentedbyanmxnintegergridimagewhereimage[i][j]representsthepixelvalueoftheimage.Youarealsogiventhreeintegerssr,sc,andcolor.Youshouldperformafloodfillontheimagestartingfromthepixelimage[sr......
  • leetcode-724-easy
    FindPivotIndexGivenanarrayofintegersnums,calculatethepivotindexofthisarray.Thepivotindexistheindexwherethesumofallthenumbersstrictlytotheleftoftheindexisequaltothesumofallthenumbersstrictlytotheindex's......
  • leetcode-744-easy
    FindSmallestLetterGreaterThanTargetYouaregivenanarrayofcharacterslettersthatissortedinnon-decreasingorder,andacharactertarget.Thereareatleasttwodifferentcharactersinletters.Returnthesmallestcharacterinlettersthatis......
  • leetcode-762-easy
    PrimeNumberofSetBitsinBinaryRepresentationGiventwointegersleftandright,returnthecountofnumbersintheinclusiverange[left,right]havingaprimenumberofsetbitsintheirbinaryrepresentation.Recallthatthenumberofsetbitsan......
  • Leetcode Practice --- 栈和队列
    目录155.最小栈思路解析20.有效的括号思路解析1047.删除字符串中的所有相邻重复项思路解析1209.删除字符串中的所有相邻重复项II思路解析删除字符串中出现次数>=2次的相邻字符剑指Offer09.用两个栈实现队列239.滑动窗口最大值思路解析155.最小栈设计一个支持push......
  • 简单理解 DP 套 DP
    复制粘贴的:通过一个外层的DP来计算使得另一个DP方程最终结果为特定值的输入数。例如求有多少种输入使得一个背包DP恰好答案为\(K\)。外层DP的状态是所有子DP的状态的值。子DP状态数很少,通常经过滚动数组优化,比如\(3n\)变成\(2\times3\))通常我们有技巧地枚......