GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — leetcode/algorithms/cpp/targetSum/targetSum.cpp at master · LumenWang/leetcode Expand file tree/ Copy pathtargetSum.cppMore file actions 59 lines (55 loc) · 1.63 KB / Copy pathtargetSum.cppFile metadata and controls59 lines (55 loc) · 1.63 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 // Source : https://leetcode.com/problems/target-sum/ // Author : Bhavesh Mandhan // Date : 2020-10-21 /********************************************************************************** * 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. * * For example, given array nums is [1, 1, 1, 1, 1], S is 3. * * There are 5 ways to assign symbols to make the sum of nums be target 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 * +1+1+1+1-1 = 3 ***********************************************************************************/ class Solution { public: int findTargetSumWays(vector<int>& nums, int S) { long int i,j,n,tot=0,sum,zero=0; n = nums.size(); for(i=0;i<n;i++){ tot+=nums[i]; if(nums[i]==0){ zero++; } } if((S+tot)%2!=0 || S>tot){ return 0; } sum = (S+tot)/2; int dp[n+1][sum+1]; for(i=1;i<=sum;i++){ dp[0][i]= 0; } for(i=0;i<=n;i++){ dp[i][0]= 1; } for(i=1;i<=n;i++){ for(j=1;j<=sum;j++){ if(nums[i-1]==0 || nums[i-1]>j){ dp[i][j] = dp[i-1][j]; } else{ dp[i][j] = dp[i-1][j] + dp[i-1][j-nums[i-1]]; } } } return pow(2,zero)*dp[n][sum]; } }; |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |