zoukankan      html  css  js  c++  java
  • leetcode permutations(全排列)

    Given a collection of distinct 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].

    这其实是一个全排列问题。具有较强的普遍性

    一开始自己想了个办法,但是这个办法每次循环都要生成一个ArrayList标记已经访问的位置,对于空间的浪费特别大。

    遂在网上查找更优的办法。该办法的核心思想就是:

    全排列就是从第一个数字起每个数分别与它后面的数字交换。

    public class Solution2 {
    
        /**
         * @param args
         */
        public   List<List<Integer>> permuteUnique(int[] nums) {
            
            
            ArrayList<List<Integer>> pool=new ArrayList<List<Integer>>();
            f(nums,0,pool);
            return pool;
            
        }
        public void f(int [] nums,int current,ArrayList<List<Integer>> pool) 
        {
            if(current==nums.length)
            {
                ArrayList<Integer> tmp=new ArrayList<Integer>();
                for(int n:nums)
                {
                    tmp.add(n);
                    
                }
                pool.add(tmp);
            }
            for(int i=current;i<nums.length;i++)
            {
                
                swap(nums,current,i);
                f(nums,current+1,pool);
                swap(nums,current,i);
                
                
            }
        
        }
        public void swap(int []nums,int i,int j)
        {
            int tmp=nums[j];
            nums[j]=nums[i];
            nums[i]=tmp;
        }
        
        
    }

    显然,该代码的核心部分是for循环。

    第一个swap交换元素,第二个swap的用意在于将交换过的元素再交换回来,保证数组的不变。

  • 相关阅读:
    第十八章 文件传输协议
    第十七章 DNS原理
    第三十六章 Linux常用性能检测的指令
    学习日报
    连接数据库综合实例
    异常处理动手动脑
    Css实例之信息提交
    JDBC编程
    将文本文件写入数据库并使用数据库读取
    Java学习
  • 原文地址:https://www.cnblogs.com/elnino/p/5457940.html
Copyright © 2011-2022 走看看