关注
public class Solution {
public static void main(String[] args) {
int[] candidates = { 5, 5, 10, 2, 3 };
int target = 15;
List<List<Integer>> res = combinationSum(candidates, target);
for (List<Integer> list : res) {
System.out.println(list);
}
}
public static List<List<Integer>> combinationSum(int[] num, int target) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
Arrays.sort(num);
Stack<Integer> stk = new Stack<Integer>();
findCombination(result, 0, target, stk, num);
return result;
}
private static void findCombination(List<List<Integer>> result, int index,
int target, Stack<Integer> stk, int[] num) {
if (target == 0) {
result.add(new ArrayList<Integer>(stk));
return;
} else {
for (int i = index; i < num.length; i++) {
if (num[i] > target)
return;
stk.push(num[i]);
findCombination(result, i + 1, target - num[i], stk, num);
stk.pop();
}
}
}
}
先对数组排序,然后利用一个栈,递归。
查看原帖
点赞 2
相关推荐
点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 今年春招是金一银二嘛? #
24662次浏览 233人参与
# 软开人,秋招你打算投哪些公司呢 #
175574次浏览 1299人参与
# 没关系,至少我的__很曼妙 #
10379次浏览 156人参与
# 帆软软件工作体验 #
9774次浏览 41人参与
# 赚钱的意义在这一刻具象化 #
10547次浏览 207人参与
# AI求职实录 #
15379次浏览 372人参与
# 关于提前批我想问 #
265156次浏览 2298人参与
# 总结:哪家公司面试体验感最好 #
79514次浏览 445人参与
# 我的秋招“寄”录 #
414545次浏览 2930人参与
# 抛开难度不谈,你最想去哪家公司? #
13459次浏览 209人参与
# 快手年终开大包 #
3336次浏览 46人参与
# 你的第一家实习公司是什么档次? #
11362次浏览 128人参与
# 为什么有人零实习也能进大厂? #
12570次浏览 227人参与
# 牛客吐槽大会 #
9060次浏览 156人参与
# 1月小结:你过的开心吗? #
4483次浏览 79人参与
# AI时代的工作 VS 传统时代的工作,有哪些不同? #
14977次浏览 351人参与
# 实习工作,你找得还顺利吗? #
564469次浏览 6664人参与
# 十一月总结 #
76435次浏览 424人参与
# 小红书求职进展汇总 #
214436次浏览 1311人参与
# Prompt分享 #
16155次浏览 375人参与
SHEIN希音公司福利 363人发布