Target Sum

来源:互联网 发布:wp10记录仪软件 编辑:程序博客网 时间:2024/06/05 02:46

题目详情:
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.

分析:
dfs暴力求解,同时在设置一个num,确认该条路是否有解,如果没有,裁枝,以加快dfs的效率。

代码如下:

class Solution {public: int total=0;void dfs(int i,vector<int>& nums,int num,int S,int s){    if(i==nums.size()){        if(s==S)        total++;        return;    }    if(num<S-s||-num>S-s) return;    dfs(i+1,nums,num-nums[i],S,s+nums[i]);    dfs(i+1,nums,num-nums[i],S,s-nums[i]);}int findTargetSumWays(vector<int>& nums, int S) {    int temp=0;    for(int i=0;i<nums.size();i++)    temp+=nums[i];            dfs(0,nums,temp,S,0);            return total;    }};
原创粉丝点击