Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8acf525

Browse files
committed
Add simple description
1 parent 58e8f6e commit 8acf525

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

‎Algorithms/Target Sum/README.md‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /