您的位置:首页 > 其它

【LeetCode】 046. Permutations

2017-01-12 23:16 405 查看
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]
]


public class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
backTrack(res, new ArrayList<Integer>(), nums);
return res;
}

private void backTrack(List<List<Integer>> res, List<Integer> subList, int[] nums) {
if (subList.size() == nums.length) {
res.add(new ArrayList<Integer>(subList));
}
for (int i = 0; i < nums.length; i++) {
if (subList.contains(nums[i])) {
continue;
}
subList.add(nums[i]);
backTrack(res, subList, nums);
subList.remove(subList.size() - 1);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: