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. 就是说给你一个一维数组 ,让你通过加和减的方式将所有的数全计算在内,然后看看有多少种方案能够达到目标数值 看到大佬都是用dp写的....dp基本不会,于是用了暴力深搜来写 代码如下:(我自己补全了测试程序) #include<iostream> #include<algorithm> #include<cstring> #include<vector> using namespace std; class Solution { public: int book[100000];// 记录vector中的数是否已经访问过了 0表示没访问过,1表示已经访问过了 int kind;//记录方案种数 void dfs(vector<int>& nums,int i,int sum,int S) { if(nums.empty()) //空的容器不可能达到目标数值,直接返回即可 return ; if(sum==S&&i==nums.size())//把所有数字全用上并且达到目标数值时,就让种数加一,并且返回上一层,看看还有没有其他方案 { kind++; return ; } if(i==nums.size())//如果数字全用上了还达不到目标数值,那就说明这种方案行不通,直接返回上一层即可 { return ; } if(!book[i]) //在没被访问过的前提下才能进行下一位的搜索,防止重复 { book[i]=1; //设置为已经访问过了 dfs(nums,i+1,sum+nums[i],S); //访问以i为下标的数*1加和的情况 dfs(nums,i+1,sum-nums[i],S);//访问以i为下标的数*(-1)加和的情况 book[i]=0; //第i位全部访问完后(第i位以及它以后的情况全部考虑完后)要将第i位设置为没有访问过,否则下一次搜索会有问题 } } int findTargetSumWays(vector<int>& nums, int S) { kind=0; memset(book,0,sizeof(book));//初始化标记数组 dfs(nums,0,0,S); int k=kind; //将种数保存在k中 return k; } }; int main() { int n,s,p; while(1) { cin>>n>>s; vector<int>q; vector<int>&q1=q;//纯粹为了和引用亲热一下,没有任何卵用 for(int i=0;i<n;++i) { cin>>p; q.push_back(p); } Solution solo; cout<<solo.findTargetSumWays(q1,s)<<endl; } }