77. 组合
leetcode题目链接:https://leetcode.cn/problems/combinations/
leetcode AC记录:
代码如下:
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new ArrayList<>(16);
List<Integer> path = new ArrayList<>(16);
hs(res, path, 1, k,n);
return res;
}
public void hs(List<List<Integer>> res, List<Integer> path, int begin, int k, int n) {
if(path.size() == k) {
res.add(new ArrayList<>(path));
return;
}
for(int i = begin; i <= n;i++) {
path.add(i);
hs(res, path, i+1, k, n);
path.remove(path.size()-1);
}
}
216.组合总和III
leetcode题目链接:https://leetcode.cn/problems/combination-sum-iii
leetcode AC记录:
代码如下:
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> res = new ArrayList<>(16);
List<Integer> path = new ArrayList<>(16);
combain(res, path, 0, k, n, 1);
return res;
}
public void combain(List<List<Integer>> res, List<Integer> path, int sum, int k, int n, int begin) {
if(sum == n && path.size() == k) {
res.add(new ArrayList<>(path));
return;
}
for(int i = begin;i <= 9;i++) {
path.add(i);
combain(res, path, sum+i, k, n, i + 1);
path.remove(path.size()-1);
}
}
17.电话号码的字母组合
leetcode题目链接:https://leetcode.cn/problems/letter-combinations-of-a-phone-number/
leetcode AC记录:
代码如下:
class Solution {
public List<String> letterCombinations(String digits) {
if(digits == null || digits.length() == 0) {
return new ArrayList<>(0);
}
List<String> res = new ArrayList<>(16);
String path = "";
hs(res, path, 0, digits.length(), 0, digits);
return res;
}
public void hs(List<String> res, String path, int curSize, int size, int beginNum, String digits) {
if(curSize == size) {
res.add(path);
return;
}
char c = digits.charAt(beginNum);
char[] str = getArray(c);
for(int i = 0;i < str.length;i++) {
hs(res, path + str[i], curSize + 1, size, beginNum + 1, digits);
}
}
public char[] getArray(char c) {
switch(c) {
case '2':
return "abc".toCharArray();
case '3':
return "def".toCharArray();
case '4':
return "ghi".toCharArray();
case '5':
return "jkl".toCharArray();
case '6':
return "mno".toCharArray();
case '7':
return "pqrs".toCharArray();
case '8':
return "tuv".toCharArray();
case '9':
return "wxyz".toCharArray();
}
return null;
}
}