zoukankan      html  css  js  c++  java
  • [leedcode 46] Permutations

    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].

    public class Solution {
        //全排列:构造一个递归函数,函数的参数一个代表开始排列的索引,一个代表最终排列的索引
        //每一位与开始位进行交换,再递归start+1到end,注意结果的保存
        List<Integer> seq;
        List<List<Integer>> res;
        public List<List<Integer>> permute(int[] nums) {
            seq=new ArrayList<Integer>();
            res=new ArrayList<List<Integer>>();
            findpermute(nums,0,nums.length-1);
            return res;
            
            
        }
        public void findpermute(int []nums,int start,int end){
            if(start>end){
                 res.add(new ArrayList<Integer>(seq));//注意要重新new一个
                return ;
            }
           
            for(int i=start;i<=end;i++){
                swap(nums,start,i);
                seq.add(nums[start]);
                findpermute(nums,start+1,end);
                seq.remove(seq.size()-1);//注意删除
                swap(nums,start,i);
            }
        }
        public void swap(int[] nums,int i,int j){
            int temp=nums[i];
            nums[i]=nums[j];
            nums[j]=temp;
        }
    }
  • 相关阅读:
    剑桥雅思写作高分范文ESSAY81
    maven安装配置
    IntelliJ IDEA 2017.3.1安装步骤
    Git基本命令整理
    jacoco覆盖率工具测试及性能分析
    OSGI框架
    查看指定库对应GCC版本
    普元eos、soa、esb
    emp架构
    jar包安装到本地仓库
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4638218.html
Copyright © 2011-2022 走看看