17. 电话号码的字母组合
public class Solution17 {
public static void main17(String[] args) {
System.out.println(letterCombinations("23"));
}
static String[] stringMap = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public static void dfs(String digits, List<String> res, String curString, int index) {
if (index == digits.length()) {
res.add(curString);
return;
}
int curIndex = digits.charAt(index) - '0';
String string = stringMap[curIndex];
for (char ch : string.toCharArray()) {
dfs(digits, res, curString + ch, index + 1);
}
}
public static List<String> letterCombinations(String digits) {
List<String> res = new ArrayList<>();
if (digits.isEmpty())
return res;
dfs(digits, res, "", 0);
return res;
}
}
401. 二进制手表
class Solution401 {
static int[] hours = new int[]{1, 2, 4, 8, 0, 0, 0, 0, 0, 0};
static int[] minutes = new int[]{0, 0, 0, 0, 1, 2, 4, 8, 16, 32};
public static void dfs(int turnedOn, int index, List<String> res, int hour, int minute) {
if (hour > 11 || minute > 59)
return;
if (turnedOn == 0) {
StringBuilder sb = new StringBuilder();
sb.append(hour).append(':');
if (minute < 10) {
sb.append('0');
}
sb.append(minute);
res.add(sb.toString());
return;
}
for (int i = index; i < 10; i++) {
dfs(turnedOn - 1, i + 1, res, hour + hours[i], minute + minutes[i]);
}
}
public static List<String> readBinaryWatch1(int turnedOn) {
List<String> res = new ArrayList<>();
dfs(turnedOn, 0, res, 0, 0);
return res;
}
public static List<String> readBinaryWatch2(int turnedOn) {
List<String> res = new ArrayList<>();
for (int i = 0; i < 12; i++) {
for (int j = 0; j < 60; j++) {
if (Integer.bitCount(i) + Integer.bitCount(j) == turnedOn) {
res.add(String.format("%d:%02d", i, j));
}
}
}
return res;
}
public static void main401(String[] args) {
System.out.println(readBinaryWatch1(1));
System.out.println(readBinaryWatch2(1));
}
}
39. 组合总和
class Solution39 {
public void dfs(int[] candidates, int target, List<List<Integer>> res, List<Integer> curRes, int curSum, int prevPos) {
if (curSum >= target) {
if (curSum == target) {
List<Integer> copy = new ArrayList<>();
for (int i = 0; i < curRes.size(); i++) {
copy.add(curRes.get(i));
}
res.add(copy);
}
return;
}
for (int i = prevPos; i < candidates.length; i++) {
if (candidates[i] > target)
continue;
curRes.add(candidates[i]);
dfs(candidates, target, res, curRes, curSum + candidates[i], i);
curRes.remove(curRes.size() - 1);
}
}
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> curRes = new ArrayList<>();
dfs(candidates, target, res, curRes, 0, 0);
return res;
}
}