【LeetCode】 46. 全排列 回溯 JAVA

心已赠人 2021-06-10 20:38 494阅读 0赞

题目

题目传送门:传送门(点击此处)
在这里插入图片描述

题解

思路

思考这道题目,很容易想到回溯,理解很容易,如下图
在这里插入图片描述
所以代码写起来,也相对的简单,不过话又说回来,这道题其实不难,还是要多刷一刷题,找到更加合适的解决方案,这个方案依旧不是最优解

代码

  1. class Solution {
  2. List<List<Integer>> res;
  3. int[] nums;
  4. public List<List<Integer>> permute(int[] nums) {
  5. this.res = new ArrayList<>();
  6. this.nums = nums;
  7. // Arrays.sort(nums); // not necessary
  8. backtrack(new ArrayList<>());
  9. return res;
  10. }
  11. private void backtrack(List<Integer> tempList) {
  12. if (tempList.size() == nums.length) {
  13. res.add(new ArrayList<>(tempList));
  14. return;
  15. }
  16. for (int i = 0; i < nums.length; i++) {
  17. if (tempList.contains(nums[i])) continue;
  18. tempList.add(nums[i]);
  19. backtrack(tempList);
  20. tempList.remove(tempList.size() - 1);
  21. }
  22. }
  23. }

发表评论

表情:
评论列表 (有 0 条评论,494人围观)

还没有评论,来说两句吧...

相关阅读

    相关 回溯——46. 排列

    1 题目描述 给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。 2 题目示例 示例 1: 输入:nums =