zoukankan      html  css  js  c++  java
  • leetcode------Permutations

    标题: Permutations
    通过率: 31.7%
    难度: 中等

    Given a collection of numbers, return all possible permutations.

    For example,
    [1,2,3] have the following permutations:
    [1,2,3][1,3,2][2,1,3][2,3,1][3,1,2], and [3,2,1].

    本题就是数字的全排列,dfs的递归,

    1、【2,3】中进行交换一次【3、2】然后加上【1】

    2、【1,2】交换一次【2,1】然后【1,3】交换一次的加上2

    3、再第二的基础上交换【2,3】,然后【1,2】交换一次加上3

    ####################

    遍历排序树的算法:(就是这样做不知道为什么)

    1         for(int j=start;j<num.length;j++){
    2             swap(num,j,start);
    3             dfs(res,num,start+1);
    4             swap(num,j,start);
    5         }

    ########################

    具体看代码:

    public class Solution {
        public ArrayList<ArrayList<Integer>> permute(int[] num) {
            ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();
            dfs(res,num,0);
            return res;
            
        }
        public void dfs(ArrayList<ArrayList<Integer>> res,int[] num,int start){
            if(start==num.length){
                ArrayList<Integer> tmp=new ArrayList<Integer>();
                for(int i=0;i<num.length;i++){
                    tmp.add(num[i]);
                }
                if(!res.contains(tmp))
                    res.add(tmp);
            }
            for(int j=start;j<num.length;j++){
                swap(num,j,start);
                dfs(res,num,start+1);
                swap(num,j,start);
            }
        }
        public void swap(int []num,int a,int b){
            int tmp=num[a];
            num[a]=num[b];
            num[b]=tmp;
        }
    }
  • 相关阅读:
    elasticsearch之python操作
    Elasticsearch之性能优化
    Elasticsearch之基本使用
    Redis主从哨兵集群搭建
    Docker Swarm集群
    Elasticsearch之权限验证(Basic)
    docker之网络与数据管理
    docker之可视化工具
    基于Github gist的代码片段管理工具Lepton
    Redis工具之redis_rdb_tools
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4357601.html
Copyright © 2011-2022 走看看