zoukankan      html  css  js  c++  java
  • 全排列

    Leetcode题目描述

    给定一个 没有重复 数字的序列,返回其所有可能的全排列。

    示例:

    输入: [1,2,3]
    输出:
    [
      [1,2,3],
      [1,3,2],
      [2,1,3],
      [2,3,1],
      [3,1,2],
      [3,2,1]
    ]
    

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/permutations
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    回溯解答

    • 问题的核心在于答案永远是三位数的,也就是排序位数永远是三位
    • 关键在于更换排序的顺序,可以依次从左到右确定顺序
    class Solution {
        public List<List<Integer>> permute(int[] nums) {
            List<Integer> tmp = new ArrayList<Integer>();
            List<List<Integer>> res = new ArrayList<>();
            int n = nums.length;
            for(int i = 0; i < n; i++){
                tmp.add(nums[i]);
            }
            backtrack(0, tmp, res, n);
            return res;
        }
    
        public void backtrack(int first, List<Integer> tmp, List<List<Integer>> res, int n){
            if(n == first){
                res.add(new ArrayList<Integer>(tmp));
            }
    
            for(int i = first; i < n; i++){
                Collections.swap(tmp, first, i);
                backtrack(first + 1, tmp, res, n);
                Collections.swap(tmp, first, i);
            }
        }
    }
    
  • 相关阅读:
    学习进度06
    求最大子数组03
    js实现标签绑定回车事件
    ImageDown
    ImageUpload
    XMLProcess
    VideoConvert
    SmtpServerHelper
    SharpZip(压缩帮助类)
    SessionHelper
  • 原文地址:https://www.cnblogs.com/Di-iD/p/13784934.html
Copyright © 2011-2022 走看看