46. Permutations

来源:互联网 发布:linux file命令 x86 编辑:程序博客网 时间:2024/05/01 01:42

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

代码(BackTracking):

public class Solution {    List<List<Integer>> list;    public List<List<Integer>> permute(int[] nums) {        list = new ArrayList<>();        ArrayList<Integer> perm = new ArrayList<Integer>();        backTrack(perm,0,nums);        return list;    }    void backTrack (ArrayList<Integer> perm,int i,int[] nums){        //Permutation completes        if(i==nums.length){            list.add(new ArrayList(perm));            return;        }        ArrayList<Integer> newPerm = new ArrayList<Integer>(perm);       //Insert elements in the array by increasing index        for(int j=0;j<=i;j++){            newPerm.add(j,nums[i]);            backTrack(newPerm,i+1,nums);            newPerm.remove(j);        }    }}

原理:
          1
   12           21
312  132  123     321  231  213

0 0
原创粉丝点击