• 图解算法——全排列(Permutations)


    1. 题目描述

    Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

    2. Examples

    示例1:

    Input: nums = [0,1]
    Output: [[0,1],[1,0]]

    示例2:

    Input: nums = [1,2,3]
    Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

    示例3:

    Input: nums = [1]
    Output: [[1]]

    输入要求:

    • 1 <= nums.length <= 6
    • -10 <= nums[i] <= 10
    • All the integers of nums are unique.

    3. 题目解析

    思路:递归枚举

    //全排列
    /*
    有两种思路:一是原地调换位置,二是树状分布
    */
    
    class Solution{
        
        //数字全排列
        public List<List<Integer>> permute(int[] nums) {
            
            List<List<Integer>> res = new List<List<Integer>>;
            List<Integer> arr = new ArrayList<Integer>;
            boolean[] is = new boolean(nums.length)//表示该下标所在字符是否存在:fasle表示不存在,true表示存在;
            search(res,arr,nums,is);
            return res;
        }
        public void search(List<List<Integer>> res, List<Integer> arr, int[] nums, boolean[] is){
            if(arr.size() == nums.length){
                res.add(arr);
                return;
            }
            for(int i = 0; i<nums.length; i++){
                if(is[i]){
                    continue;
                }
                is[i] = true;
                arr.add(nums[i]);
                search(res,arr,nums,is);  //是一个子问题
                arr.remove(nums[i]);
                is[i] = false;
            }
        }
        //字符串全排列
        public void permute1(string str) {
            char[] chs = str.toCharArray();
            List<String> res = new ArrayList<String>;
            process(res,chs,0);
        }
        
        public void process(List<String> res, char[] chs,int i){
            if(i==chs.length){
                res.add(chs.toString());
                return;
            }
            for(int j=i; j<chs.length; j++){
                swap(chs,i,j);
                process(res,chs,++i);
                swap(chs,i,j);
            }
        }
        public void process(char[] chs,int i,int j){
            int temp = chs[i];
            chs[i] = chs[j];
            chs[j] = temp;
        }
    }

    还有类似的题目见:左神算法第八节课:介绍递归和动态规划

    Over...

  • 相关阅读:
    JS复制内容到剪切板
    mysql root密码的重设方法(转)
    php生成excel文件示例代码(转)
    php读取文件内容的三种方式(转)
    使用火蜘蛛采集器Firespider采集天猫商品数据并上传到微店
    Mac Android8.0源码编译笔记
    开源 高性能 高可用 可扩展
    开源 模式
    开源 算法 数据结构
    mdb
  • 原文地址:https://www.cnblogs.com/gjmhome/p/14398899.html
Copyright © 2020-2023  润新知