Skip to content

Commit

Permalink
Merge pull request youngyangyang04#1403 from Damon0820/master
Browse files Browse the repository at this point in the history
添加(0015.三数之和.md):增加javascript版本nsum的通用解法
  • Loading branch information
youngyangyang04 authored Jun 28, 2022
2 parents 1ca56dd + 4e95d66 commit c6a4ea6
Show file tree
Hide file tree
Showing 2 changed files with 88 additions and 0 deletions.
70 changes: 70 additions & 0 deletions problems/0015.三数之和.md
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,76 @@ var threeSum = function(nums) {
return res
};
```

解法二:nSum通用解法。递归

```js
/**
* nsum通用解法,支持2sum,3sum,4sum...等等
* 时间复杂度分析:
* 1. n = 2时,时间复杂度O(NlogN),排序所消耗的时间。、
* 2. n > 2时,时间复杂度为O(N^n-1),即N的n-1次方,至少是2次方,此时可省略排序所消耗的时间。举例:3sum为O(n^2),4sum为O(n^3)
* @param {number[]} nums
* @return {number[][]}
*/
var threeSum = function (nums) {
// nsum通用解法核心方法
function nSumTarget(nums, n, start, target) {
// 前提:nums要先排序好
let res = [];
if (n === 2) {
res = towSumTarget(nums, start, target);
} else {
for (let i = start; i < nums.length; i++) {
// 递归求(n - 1)sum
let subRes = nSumTarget(
nums,
n - 1,
i + 1,
target - nums[i]
);
for (let j = 0; j < subRes.length; j++) {
res.push([nums[i], ...subRes[j]]);
}
// 跳过相同元素
while (nums[i] === nums[i + 1]) i++;
}
}
return res;
}

function towSumTarget(nums, start, target) {
// 前提:nums要先排序好
let res = [];
let len = nums.length;
let left = start;
let right = len - 1;
while (left < right) {
let sum = nums[left] + nums[right];
if (sum < target) {
while (nums[left] === nums[left + 1]) left++;
left++;
} else if (sum > target) {
while (nums[right] === nums[right - 1]) right--;
right--;
} else {
// 相等
res.push([nums[left], nums[right]]);
// 跳过相同元素
while (nums[left] === nums[left + 1]) left++;
while (nums[right] === nums[right - 1]) right--;
left++;
right--;
}
}
return res;
}
nums.sort((a, b) => a - b);
// n = 3,此时求3sum之和
return nSumTarget(nums, 3, 0, 0);
};
```

TypeScript:

```typescript
Expand Down
18 changes: 18 additions & 0 deletions problems/0509.斐波那契数.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,7 @@ func fib(n int) int {
}
```
### Javascript
解法一
```Javascript
var fib = function(n) {
let dp = [0, 1]
Expand All @@ -244,6 +245,23 @@ var fib = function(n) {
return dp[n]
};
```
解法二:时间复杂度O(N),空间复杂度O(1)
```Javascript
var fib = function(n) {
// 动规状态转移中,当前结果只依赖前两个元素的结果,所以只要两个变量代替dp数组记录状态过程。将空间复杂度降到O(1)
let pre1 = 1
let pre2 = 0
let temp
if (n === 0) return 0
if (n === 1) return 1
for(let i = 2; i <= n; i++) {
temp = pre1
pre1 = pre1 + pre2
pre2 = temp
}
return pre1
};
```

TypeScript

Expand Down

0 comments on commit c6a4ea6

Please sign in to comment.