字符的排列组合问题,使用递归+回溯方法。对于有重复元素或者需要组合的元素具有一定顺序,需要先进行排序。
排列问题因为对所有元素进行排列,判断是否为结果的条件是list的大小和数组的长度相同,否则,依次将没有排列的元素添加到list中,结束一次排列后需要回溯;对于数组元素唯一,只需要在循环中判断list中是否包含该元素,不包含,进行添加,否则,跳过。对于数组元素不唯一,设置Boolean数组来标记是否访问过,并对重复出现的组合去重。
组合问题相当于对N个元素,挑选M个元素进行全排列,需要将M作为参数进行传递 ,并设置当m==0时结束一次组合,m<0时返回。对于非递减组合,需要事先对数组进行排序,如果结果需要按照size的大小进行排序输出,可以在排列时通过for循环传入m的值,对于数组元素不唯一,可在将元素添加到list中时进行判断,由于已经进行排序,所以,只需要判定当前值与前一个元素不同即可,保证同一层搜索时只选一次一个相同的数。
常见题解答(均已AC):
1.数组元素唯一的全排列:(LeetCode :permutations)
Given a collection of 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], and[3,2,1].
import java.util.*;
public class Solution {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
public ArrayList<ArrayList<Integer>> permute(int[] num) {
ArrayList<Integer> list = new ArrayList<Integer>();
dfs(num,list);
return result;
}
public void dfs(int[] num ,ArrayList<Integer> list) {
if(list.size() == num.length){
result.add(new ArrayList<Integer>(list));
}else{
for(int i = 0 ;i<num.length;i++){
if(list.contains(num[i]))
continue;
list.add(num[i]);
dfs(num,list);
list.remove(list.size()-1);
}
}
}
}
2.数组元素不唯一的全排列:(LeetCode: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], and[2,1,1].
import java.util.*;
public class Solution {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
ArrayList<Integer> list = new ArrayList<Integer>();
boolean visited[] = new boolean[num.length];
Arrays.sort(num);
df