数组的子序列

代码实现

  1. /**
  2. * 数组子序列
  3. * @param {*} arr
  4. * @returns
  5. */
  6. function subsequence(arr) {
  7. const ans = [];
  8. function dfs(index, path) {
  9. if (index === arr.length) {
  10. ans.push(path);
  11. return;
  12. }
  13. // 取当前值
  14. dfs(index + 1, [...path, arr[index]]);
  15. // 不取当前值
  16. dfs(index + 1, [...path]);
  17. return ans;
  18. }
  19. return dfs(0, []);
  20. }
JavaScript

测试

  1. console.log(subsequence([1, 2, 3]));
  2. // [
  3. // [ 1, 2, 3 ], [ 1, 2 ],
  4. // [ 1, 3 ], [ 1 ],
  5. // [ 2, 3 ], [ 2 ],
  6. // [ 3 ], []
  7. // ]
JavaScript
编程笔记 & 随笔杂谈