您的位置:首页 > 其它

46. Permutations

2016-03-07 17:16 288 查看

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: