https://leetcode-cn.com/problems/subsets/

深度优先遍历

  • 每个位置要or不要,构成一颗树,到达最底部收集答案

image.png

  1. public List<List<Integer>> subsets(int[] nums) {
  2. List<List<Integer>> ans = new ArrayList<>();
  3. LinkedList path = new LinkedList();
  4. process(nums, 0, ans, path);
  5. return ans;
  6. }
  7. /*
  8. 当前来到index位置,做决定 1) 要当前位置的数 2)不要当前位置的数
  9. 如果要当前位置的数, 把该数字,放入到path中去,
  10. 如果不要当前位置的数, 不放入path中
  11. */
  12. private void process(int[] nums, int index, List<List<Integer>> ans, LinkedList path) {
  13. if (index == nums.length) {
  14. ans.add(copy(path));
  15. } else {
  16. // 要当前这个数
  17. path.add(nums[index]);
  18. process(nums, index + 1, ans, path);
  19. // 恢复现场
  20. path.removeLast();
  21. // 不要当前这个数
  22. process(nums, index + 1, ans, path);
  23. }
  24. }
  25. private ArrayList<Integer> copy(LinkedList<Integer> path) {
  26. ArrayList<Integer> ans = new ArrayList<>();
  27. for (Integer num : path) {
  28. ans.add(num);
  29. }
  30. return ans;
  31. }