494. Target Sum 494.目標總和
阿新 • • 發佈:2020-07-25
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.
思路:試試回溯:
dfs(int[] nums, int S, )
數量不知道該放在哪裡
其實為了湊出來一個和,引數裡有個pos, 然後sum + nums[pos]就行了
return ; //position到頭之後,無論如何都要退出一下
兩個DFS都進行就行:
dfs(nums, pos + 1, currentSum + nums[pos], S);
dfs(nums, pos + 1, currentSum - nums[pos], S);
class Solution { int count; public int findTargetSumWays(intView Code[] nums, int S) { //cc if (nums == null || nums.length == 0) count = 0; //dfs dfs(nums, 0, 0, S); return count; } public void dfs(int[] nums, int pos, int currentSum, int S) { //exit if (pos == nums.length) {if (currentSum == S) count++; return ; //無論如何都要退出一下 } dfs(nums, pos + 1, currentSum + nums[pos], S); dfs(nums, pos + 1, currentSum - nums[pos], S); } }