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

 

posted @ 2016-05-04 12:00  ElNinoT  阅读(257)  评论(0编辑  收藏  举报