day27 打卡39. 组合总和 40.组合总和II 131.分割回文串
day27 打卡39. 组合总和 40.组合总和II 131.分割回文串
39. 组合总和
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
backtracking(candidates, target, 0, 0);
return result;
}
private void backtracking (int[] candidates, int target, int sum, int idx) {
if (sum > target) return;
if (sum == target) {
result.add(new LinkedList<>(path));
return;
}
for (int i = idx; i < candidates.length; i++) {
// 如果 sum + candidates[i] > target 就终止遍历
if (sum + candidates[i] > target) break;
path.add(candidates[i]);
backtracking(candidates, target, sum + candidates[i], i);
path.remove(path.size() - 1); // 回溯,移除路径 path 最后一个元素
}
}
}
40.组合总和II
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
boolean[] used;
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
used = new boolean[candidates.length];
Arrays.sort(candidates);
backTracking(candidates, target, 0, 0);
return result;
}
private void backTracking(int[] candidates, int target, int startIndex, int sum) {
if (sum > target) return;
if (sum == target) {
result.add(new ArrayList<>(path));
}
for (int i = startIndex ; i<candidates.length ; i++) {
if (sum + candidates[i] > target) break;
if (i>0 && candidates[i]==candidates[i-1] && !used[i-1]) continue;
used[i] = true;
sum += candidates[i];
path.add(candidates[i]);
backTracking(candidates, target, i+1, sum);
used[i] = false;
sum -= candidates[i];
path.removeLast();
}
}
}
131.分割回文串
class Solution {
List<List<String>> result = new ArrayList<>();
Deque<String> que = new LinkedList<>();
public List<List<String>> partition(String s) {
backtracking(s, 0);
return result;
}
private void backtracking(String s, int startIndex) {
if (startIndex >= s.length()) {
result.add(new ArrayList<>(que));
return;
}
for (int i = startIndex ; i<s.length() ; i++) {
if (isPalindrome(s, startIndex, i)) {
que.addLast(s.substring(startIndex, i+1));
} else {
continue;
}
backtracking(s, i+1);
que.removeLast();
}
}
private boolean isPalindrome(String s, int startIndex, int end) {
for (int i=startIndex, j=end; i<=j ; i++, j--) {
if (s.charAt(i) != s.charAt(j))
return false;
}
return true;
}
}
参考资料
分类:
LeetCode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?