Skip to content

Commit 15afb60

Browse files
committed
数组、递归增加
数组:数组元素concat 递归:爬阶梯算法
1 parent 9a8e28c commit 15afb60

File tree

2 files changed

+58
-1
lines changed

2 files changed

+58
-1
lines changed

js/array.js

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -279,4 +279,26 @@ function queryFirstUniqueItemTest() {
279279
var ret = queryFirstUniqueItem(a);
280280
console.log('ret: ', ret);
281281
console.log('ret: ', !ret);
282-
}
282+
}
283+
284+
// 给一个数组如:[[“a”,”b”,”c”],[“d”,”e”],…..]得到[ad,ae,bd,be,cd,ce]
285+
function mapConcat(target) {
286+
var res = target.reduce(function (pre, next) {
287+
var ret = [];
288+
pre.forEach(function (preItem) {
289+
next.forEach(function (nextItem) {
290+
if (preItem !== nextItem) { // 去掉aa这种情况
291+
ret.push(preItem + nextItem);
292+
}
293+
})
294+
})
295+
return ret;
296+
})
297+
return res;
298+
}
299+
function mapConcatTest() {
300+
// var target = [['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h'], ['j', 'm']];
301+
var target = [['a', 'b', 'c'], ['a', 'b']];
302+
console.log('\nmapConcatTest:\n', mapConcat(target));
303+
}
304+
mapConcatTest()

js/recursive.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* @authors : qieguo
3+
* @date : 2017/1/2 0002
4+
* @version : 1.0
5+
* @description : 一些递归算法
6+
*/
7+
8+
'use strict';
9+
10+
// 假设一个楼梯有 N 阶台阶,人每次最多可以跨 M 阶,求总共的爬楼梯方案数。
11+
// 例如楼梯总共有3个台阶,人每次最多跨2个台阶,也就是说人每次可以走1个,也可以走2个,但最多不会超过2个,那么楼梯总共有这么几种走法:
12+
// 111,12,21
13+
// 5,3 => 3/2
14+
15+
function getStepMethodNum(steps, max) {
16+
var sumStep = 0;
17+
//总台阶数为0时,终止递归循环
18+
if (steps === 0) {
19+
return 1;
20+
}
21+
if (steps >= max) {
22+
//如果steps大于每步最大台阶数,则设置第一步为m之内的一个台阶数,然后递归循环
23+
for (var i = 1; i <= max; i++) {
24+
sumStep += getStepMethodNum(steps - i, max);
25+
}
26+
} else {
27+
//如果steps小于m,则将一步最大台阶数缩小为steps,重新递归
28+
sumStep = getStepMethodNum(steps, steps);
29+
}
30+
return sumStep;
31+
}
32+
function getStepMethodNumTest() {
33+
console.log('\n getStepMethodNumTest: \n', getStepMethodNum(3,4));
34+
}
35+
getStepMethodNumTest()

0 commit comments

Comments
 (0)