注:此博客不再更新,所有最新文章将发表在个人独立博客limengting.site。分享技术,记录生活,欢迎大家关注
- 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],
[3,2,1]
]
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
backtrack(res, new ArrayList<Integer>(), nums);
return res;
}
private void backtrack(List<List<Integer>> res, List<Integer> tmp, int[] nums) {
if (tmp.size() == nums.length)
res.add(new ArrayList<Integer>(tmp));
for (int i = 0; i < nums.length; i ++) {
if (tmp.contains(nums[i])) continue;
tmp.add(nums[i]);
backtrack(res, tmp, nums);
tmp.remove(tmp.size() - 1);
}
}
}
- Permutations II
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2] have the following unique permutations:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
这里写代码片