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的用意在于将交换过的元素再交换回来,保证数组的不变。

  • 相关阅读:
    我的WCF之旅(1):创建一个简单的WCF程序
    c#自定义类型的转换方式operator,以及implicit(隐式)和explicit (显示)声明的区别
    Linux 系统时间设置
    Redis入门
    线程安全的单例模式
    redis-Sentinel配置
    openpose
    Qt5.11参考文档
    opencv3.3
    opencv3.4 win10 visual studio2017 opencv_contrib 编译
  • 原文地址:https://www.cnblogs.com/elnino/p/5457940.html
Copyright © 2011-2022 走看看