46 Permutations
https://leetcode.com/problems/permutations/#/description
Given a collection ofdistinctnumbers, 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]
]
分析及代码
因为permutation每一次都要从头走,所以需要标记哪些元素已经用过了
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if(nums.length == 0) {
return res;
}
boolean[] used = new boolean[nums.length];
generate(res, new ArrayList<>(), nums, used);
return res;
}
private void generate(List<List<Integer>> res, List<Integer> item, int[] nums, boolean[] used) {
if(item.size() == nums.length) {
res.add(new ArrayList<>(item));
return;
}
for(int i = 0; i < nums.length; i++) {
if(!used[i]) {
used[i] = true;
item.add(nums[i]);
generate(res, item, nums, used);
used[i] = false;
item.remove(item.size() - 1);
}
}
}
O(n!)