|
| 1 | +Think it over straightly, we could quickly find a way to solve it. For each integer, we could have two choices, the length of array is 20 at most, so the total time complexity will be O(2^20), about 100w, but get a TLE! |
| 2 | + |
| 3 | +```javascript |
| 4 | +/** |
| 5 | + * @param {number[]} nums |
| 6 | + * @param {number} S |
| 7 | + * @return {number} |
| 8 | + */ |
| 9 | +var findTargetSumWays = function(nums, S) { |
| 10 | + let ans = 0 |
| 11 | + , len = nums.length; |
| 12 | + |
| 13 | + let dfs = (index, sum) => { |
| 14 | + if (index === len) { |
| 15 | + if (sum === S) |
| 16 | + ans++; |
| 17 | + return; |
| 18 | + } |
| 19 | + |
| 20 | + dfs(index + 1, sum - nums[index]); |
| 21 | + dfs(index + 1, sum + nums[index]); |
| 22 | + }; |
| 23 | + |
| 24 | + dfs(0, 0); |
| 25 | + |
| 26 | + return ans; |
| 27 | +}; |
| 28 | +``` |
| 29 | + |
| 30 | +It's strange and unbelievable to me, 100w is a normal time complexity in my memory. (**Is there something wrong in my code?**) |
| 31 | + |
| 32 | +Then I think about it in the opposite way, `sum` is the sum of elements, and `S` is the target, what about `sum - S`? The question can transform to, how many ways to choose from the array that added up the `(sum - S) / 2` (think about why not `sum - S`?)? The solution is [here](https://github.com/hanzichi/leetcode/blob/master/Algorithms/Target%20Sum/dfs-solution.js), it's not a good solution, for the time complexity is still O(2^20), with some prunings, finally pass it with over 1000ms. |
| 33 | + |
| 34 | +Look back to the question, we miss a piece of important information that **The sum of elements in the given array will not exceed 1000**, so I write down the [following solution ](https://github.com/hanzichi/leetcode/blob/master/Algorithms/Target%20Sum/better-solution.js) with time complexity O(20*1000) at most, obviously getting an much quicker solution. |
0 commit comments