zoukankan      html  css  js  c++  java
  • LeetCode 494. Target Sum

    You are given a list of non-negative integers, a1, a2, …, an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and – as its new symbol.

    Find out how many ways to assign symbols to make sum of integers equal to target S.

    Example 1:

    Input: nums is [1, 1, 1, 1, 1], S is 3.
    Output: 5
    Explanation:
    -1+1+1+1+1 = 3
    +1-1+1+1+1 = 3
    +1+1-1+1+1 = 3
    +1+1+1-1+1 = 3
    +1+1+1+1-1 = 3

    There are 5 ways to assign symbols to make the sum of nums be target 3.

    Note:

    • The length of the given array is positive and will not exceed 20.
    • The sum of elements in the given array will not exceed 1000.
    • Your output answer is guaranteed to be fitted in a 32-bit integer.

    分析

    题目的意思等价于把题目中给定的集合中挑选元素分成两个集合,set1,set2,然后用set1的和减去set2的和等于S。
    set1-set2=S;
    set1-(sum-set1)=S;
    set1=(S+sum)/2;
    所以题目转化成在集合中挑选元素使其和为(S+sum)/2.

    class Solution {
    public:
        int findTargetSumWays(vector<int>& nums, int S) {
            int sum=accumulate(nums.begin(),nums.end(),0);
            return sum<S||(S+sum)%2>0?0:Sumset(nums,(S+sum)/2);
        }
        int Sumset(vector<int>& nums,int s){
            int dp[s+1]={0};
            dp[0]=1;
            for(auto num:nums)
                for(int i=s;i>=num;i--)
                    dp[i]+=dp[i-num];
            return dp[s];
        }
    };
    
    

    这道题用dfs也可以,尝试为每个数前面添加 + 或 -。

    class Solution {
    public:
        int res=0;
        void dfs(int cnt,int sum,vector<int>& nums,int S){
            if(cnt==nums.size()){
                if(sum==S)
                 res++;  
                 return ;
            }      
            dfs(cnt+1,sum+nums[cnt],nums,S);
            dfs(cnt+1,sum-nums[cnt],nums,S);
        }
        int findTargetSumWays(vector<int>& nums, int S) {
            dfs(0,0,nums,S);
            return res;
        };
    };
    
    
  • 相关阅读:
    每天一道LeetCode--141.Linked List Cycle(链表环问题)
    每天一道LeetCode--119.Pascal's Triangle II(杨辉三角)
    每天一道LeetCode--118. Pascal's Triangle(杨辉三角)
    CF1277D Let's Play the Words?
    CF1281B Azamon Web Services
    CF1197D Yet Another Subarray Problem
    CF1237D Balanced Playlist
    CF1239A Ivan the Fool and the Probability Theory
    CF1223D Sequence Sorting
    CF1228D Complete Tripartite
  • 原文地址:https://www.cnblogs.com/A-Little-Nut/p/10061285.html
Copyright © 2011-2022 走看看