-
Notifications
You must be signed in to change notification settings - Fork 0
46. Permutations
Jacky Zhang edited this page Aug 26, 2016
·
2 revisions
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] ]
解题思路为backtracking。mark已使用过的数字。
public class Solution {
private boolean[] used;
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
used = new boolean[nums.length];
helper(nums, new ArrayList<Integer>(), res);
return res;
}
private void helper(int[] nums, List<Integer> list, List<List<Integer>> res) {
if(list.size() == nums.length) {
res.add(new ArrayList<Integer>(list));
return;
}
for(int i = 0; i < nums.length; i++) {
if(used[i]) continue;
list.add(nums[i]);
used[i] = true;
helper(nums, list, res);
used[i] = false;
list.remove(list.size()-1);
}
}
}