permutations

Description:

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],
  [3,2,1]
]

 Thoughts:

给定了一个非重复的数组,要知道给定数组的所有的排列方式。我们知道这个一个排列的长度必定是nums.length,选定第一个数字的时候,我们要对给定数组进行一次遍历,选第二个数字的时候 ,我们再次对数组进行一次遍历并且跳过第一个数字,选第三个数字的时候,我们再次遍历数组并且跳过第一个和第二个数字,以此类推,我们将会得到最终的结果。

算法是简单的,这里我们再次使用回溯的算法思想,如果当前得到的templist.length等于nums.length,那么说明templist是属于给定的nums的一个排列,否则我们就继续往templist中添加数字。

以下是java代码

package middle;

import java.util.ArrayList;
import java.util.List;

public class Permutations {
    public List<List<Integer>> permute(int[] nums){
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        int length = nums.length;
        trackback(nums, new ArrayList(),result);
        return result;
    }

    private void trackback(int[] nums, ArrayList tempList, List<List<Integer>> result) {
        // TODO Auto-generated method stub
        if(tempList.size() == nums.length){
            result.add(new ArrayList(tempList));
        }else{
            for(int i = 0; i < nums.length;i++){
                // 当前的数字已经在templist中,而排列是不允许重复的,所以就需要跳过这个数字
                if(tempList.contains(nums[i]))
                    continue;
                tempList.add(nums[i]);
                trackback(nums, tempList, result);
                // 当前这个数字的所有的可能已经全部遍历过了,现在回退,进入另一个分支
                tempList.remove(tempList.size() - 1);
                
            }
        }
        
    }
    
    
    public static void main(String[] args){
        Permutations p = new Permutations();
        int[] nums = new int[]{1,2,3};
        List<List<Integer>> result = p.permute(nums);
        System.out.println(result);
    }
 
原文地址:https://www.cnblogs.com/whatyouknow123/p/7501415.html