class Solution {
List<List<Integer>> res;
LinkedList<Integer> path;
int sum;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
res = new ArrayList<>();
path = new LinkedList<>();
sum = 0;
//需要排序,否则值小的数无法进入解空间
Arrays.sort(candidates);
backtracking(candidates, target, 0);
return res;
}
private void backtracking(int [] candidates, int target, int s) {
if (sum == target) {
res.add(new ArrayList<>(path));
return;
}
//剪枝 大于即将成为sum值大于target就没必要继续了
for (; s < candidates.length && sum + candidates[s] <= target; s++) {
path.add(candidates[s]);
sum += candidates[s];
backtracking(candidates, target, s);
path.removeLast();
sum -= candidates[s];
}
}
}

class Solution {
private List<String> res;
private StringBuilder path;
public List<String> letterCombinations(String digits) {
res = new ArrayList<>();
if (digits == null || digits.equals("")) return res;
path = new StringBuilder();
//存入需要操作的
String[] reflect = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
List<String> need = new ArrayList<>();
for (int c : digits.toCharArray()) {
//排除输入1
if (c >= '2' || c <= '9')
need.add(reflect[c - '2']);
}
backtracking(need, 0);
return res;
}
private void backtracking(List<String> need, int i) {
if (path.length() == need.size()) {
res.add(new String(path));
return;
}
for (char c : need.get(i).toCharArray()) {
path.append(c);
backtracking(need, i + 1);
path.deleteCharAt(path.length() - 1);
}
}
}

参考:programmercarl.com
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异