您的位置:首页 > 其它

深度优先-Leetcode46 全排列

2017-06-23 12:55 357 查看
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].

深度优先的框架:

public class Solution {
//深度优先 的框架
public static List<List<Integer>> ans = new ArrayList<List<Integer>>();
public static int[] path = new int[100];
public static boolean[] v = new boolean[100];

public static void robot(int idx, int[] nums){
if(idx >= nums.length){
List<Integer> tmp = new ArrayList<Integer>();
for(int i = 0; i < nums.length; i++){
tmp.add(nums[path[i]]);
}
ans.add(tmp);
return;
}
for(int i = 0; i < nums.length; i++){
if(v[i] == false){
path[idx] =i;
v[i] = true;
robot(idx+1, nums);
v[i] = false;
}
}
}

public List<List<Integer>> permute(int[] nums) {
ans.clear();
robot(0,nums);
return ans;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐