数组的子序列
代码实现
- /**
- * 数组子序列
- * @param {*} arr
- * @returns
- */
- function subsequence(arr) {
- const ans = [];
- function dfs(index, path) {
- if (index === arr.length) {
- ans.push(path);
- return;
- }
- // 取当前值
- dfs(index + 1, [...path, arr[index]]);
- // 不取当前值
- dfs(index + 1, [...path]);
- return ans;
- }
- return dfs(0, []);
- }
JavaScript
测试
- console.log(subsequence([1, 2, 3]));
- // [
- // [ 1, 2, 3 ], [ 1, 2 ],
- // [ 1, 3 ], [ 1 ],
- // [ 2, 3 ], [ 2 ],
- // [ 3 ], []
- // ]
JavaScript