leetcode 全排列

题目链接

1. 题目考点

  1. 回溯算法
  2. N叉树的遍历
  3. bfs
  4. dfs

2. 考点解析

  1. bfs 解法 模板
class Solution {
    List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> permute(int[] nums) {
      backTrace(nums);
      return res;
    }

    public void backTrace(int[] nums) {
      Queue<Queue<Integer>> queue = new LinkedList<>();
      Queue<Integer> q = new LinkedList<>();
      queue.offer(q);
      while (!queue.isEmpty()) {
        q = queue.poll();
        if (q.size() == nums.length) res.add(new ArrayList(q));
        else {
          // 关键:temp 在 q 基础上操作
          Stack<Integer> temp = new LinkedList<>(q);
          for (int n : nums) {
            if (!q.contains(n)) {
              temp.offer(n);
              queue.offer(new LinkedList(temp));
              // 关键:回退
              temp.remove(n);
            }
          }
        }   
      }
    }  
}
  1. dfs 解法 n叉树先序遍历 + 回退操作
class Solution {
    List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> permute(int[] nums) {
      // 优化:path 每次在末尾操作 逻辑上是一个栈
      Stack<Integer> path = new Stack<>();
      backTrace(nums, path);
      return res;
    }

    public void backTrace(int[] nums, Stack<Integer> path) {
      if (path.size() == nums.length) {
        res.add(new ArrayList(path));
        return ;
      }
	  // 本质:n 叉树bfs
      for (int n : nums) {
        if (path.contains(n)) continue;
        path.push(n);
        backTrace(nums, path);
        path.pop();
      }
    }  
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值