Permutations I
Problem
Given a list of numbers, return all possible permutations.
Example
For nums = [1,2,3], the permutations are:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
Challenge
Do it without recursion.
Solution
Recursion
class Solution {
public ArrayList<ArrayList<Integer>> permute(ArrayList<Integer> num) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
if (num == null || num.size() == 0) {
return res;
}
ArrayList<Integer> list = new ArrayList<Integer> ();
helper (nuts, list, res);
return res;
}
public void helper(ArrayList<Integer> num, ArrayList<Integer> list, ArrayList<ArrayList<Integer>> res) {
if (list.size() == num.size()) {
res.add(new ArrayList<Integer> (list));
return;
}
for (int i = 0; i < num.size(); i++) {
if (list.contains(num.get(i))) {
continue;
}
list.add(num.get(i));
helper(num, list, res);
list.remove(list.size() - 1);
}
}
}
Permutations II
Problem
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
Example:
Input: [1,1,2]
Output:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
Solution
- sort
- call backtracking function in main function
- in backtracking function, when temp list size equals nums array size, save a copy of temp list to result
- iteration nums array, if current num is used, or it's same as previous num and previous num is unused (released), continue
- update temp array and used boolean array at the same time in back tracking.
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null || nums.length == 0) return res;
Arrays.sort(nums);
helper(nums, new ArrayList<Integer>(), new boolean[nums.length], res);
return res;
}
private void helper(int[] nums, List<Integer> temp, boolean[] used, List<List<Integer>> res) {
if (temp.size() == nums.length) res.add(new ArrayList<>(temp));
else {
for (int i = 0; i < nums.length; i++) {
if (used[i] || (i > 0 && !used[i-1] && nums[i] == nums[i-1])) {
continue;
} else {
used[i] = true;
temp.add(nums[i]);
helper(nums, temp, used, res);
temp.remove(temp.size()-1);
used[i] = false;
}
}
}
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。