17.电话号码的字母组合
class Solution {
List<String> res = new ArrayList<>();
// 设置电话号
String numbers[] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
StringBuilder letter = new StringBuilder();
public List<String> letterCombinations(String digits) {
if(digits == null || digits.length() == 0){
return res;
}
backtracking(digits , letter , 0);
return res;
}
public void backtracking(String digits , StringBuilder letter , int index){
if(digits.length() == letter.length()){
// 如果数字符合 则添加
res.add(letter.toString());
return;
}
// 得到当前numbers哪个电话号
String str = numbers[digits.charAt(index) - '0'];
for(int i = 0; i < str.length();i++){
// 添加进letter
letter.append(str.charAt(i));
backtracking(digits,letter,index + 1);
letter.deleteCharAt(letter.length()-1);
}
}
}
46.全排列
class Solution {
public List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> list = new LinkedList<>();
public List<List<Integer>> permute(int[] nums) {
if(nums.length == 0)return res;
boolean used[] = new boolean[nums.length];
backtracking(nums , used);
return res;
}
public void backtracking(int[] nums, boolean[] used){
if(nums.length == list.size()){
res.add(new ArrayList(list));
return;
}
for(int i = 0; i < nums.length; i ++){
if(used[i] == true)continue;
list.add(nums[i]);
used[i] = true;
backtracking(nums, used);
list.removeLast();
used[i] = false;
}
}
}
设置多一个used数组,判断其是否用过