数字排列-38-1
输入一组数字,输出其所有的排列方式。
样例
输入:[1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
思路:
回溯法
class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> permute(int[] nums) {
boolean[] visited = new boolean[nums.length];
backtrack(nums, new ArrayList<Integer>(), visited);
return res;
}
private void backtrack(int[] nums, ArrayList<Integer> tmp, boolean[] visited) {
if (tmp.size() == nums.length) {
res.add(new ArrayList<>(tmp));
return;
}
for (int i = 0; i < nums.length; i++) {
if (visited[i]) continue;
visited[i] = true;
tmp.add(nums[i]);
backtrack(nums, tmp, visited);
visited[i] = false;
tmp.remove(tmp.size() - 1);
}
}
}
依次将第一个数字和后面的数字进行交换:
class Solution {
public void backtrack(int n, ArrayList<Integer> nums,
List<List<Integer>> output, int first) {
if (first == n)
output.add(new ArrayList<Integer>(nums));
for (int i = first; i < n; i++) {
Collections.swap(nums, first, i);
backtrack(n, nums, output, first + 1);
Collections.swap(nums, first, i);
}
}
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> output = new LinkedList();
ArrayList<Integer> nums_lst = new ArrayList<Integer>();
for (int num : nums) nums_lst.add(num);
int n = nums.length;
backtrack(n, nums_lst, output, 0);
return output;
}
}
数字排列-38-2
输入一组数字(可能出现重复数字),输出其所有的排列方式。
样例
输入:[1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
思路:
回溯法,先给数组排序,然后在判断数组元素是否访问过的同时,判断是否出现重复元素
class Solution {
List<List<Integer>> res = new ArrayList();
public List<List<Integer>> permutation(int[] nums) {
Arrays.sort(nums);
boolean[] visited = new boolean[nums.length];
List<Integer> list = new ArrayList<>();
backtrack(nums, list, visited);
return res;
}
public void backtrack(int[] nums, List<Integer> list, boolean[] visited){
if(list.size() == nums.length){
res.add(new ArrayList<>(list));
return;
}
for(int i = 0; i < nums.length; i++){
if(visited[i] || (i > 0 && !visited[i-1] && nums[i] == nums[i-1]) ) continue;
visited[i] = true;
list.add(nums[i]);
backtrack(nums, list, visited);
list.remove(list.size()-1);
visited[i] = false;
}
}
}