leetcode 39 java dfs
程序员文章站
2022-07-07 18:56:41
...
Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
- All numbers (including target) will be positive integers.
- The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7]
and target 7
,
A solution set is:
[
[7],
[2, 2, 3]
]
对于输入candidates=[1,2] ,target=3,遍历的方向如图:
AC代码
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<Integer> path =new ArrayList<Integer>();
List<List<Integer>> result=new ArrayList<>();
Arrays.sort(candidates);
dfs(candidates,0,0,target,path,result);
return result;
}
private void dfs(int[] a, int now, int sum, int target,List<Integer> path,
List<List<Integer>> result) {
// TODO Auto-generated method stub
if(sum==target){
result.add(new ArrayList<>(path));
return ;
}
if(sum>target){
return ;
}
for(int i=now;i<a.length;i++){
if(sum+a[i]>target){
break;
}
path.add(a[i]);
System.out.println("dfs("+i+")");
dfs(a,i,sum+a[i],target,path,result);
path.remove(path.size()-1);
}
}
}
推荐阅读
-
java编程无向图结构的存储及DFS操作代码详解
-
leetcode.字符串.344反转字符串-Java
-
DFS和BFS讲解及Leetcode刷题小结(1)(JAVA)
-
【每日一道算法题】Leetcode之longest-increasing-path-in-a-matrix矩阵中的最长递增路径问题 Java dfs+记忆化
-
[Leetcode][第410题][JAVA][分割数组的最大值][动态规划][二分]
-
LeetCode 151. 翻转字符串里的单词(java代码和思路分析,模拟题)
-
LeetCode 热题 HOT 100 Java题解——148. 排序链表
-
Java,LeetCode 21. 合并两个有序链表
-
如何在Intellij中安装LeetCode刷题插件方便Java刷题
-
Leetcode 2. Add Two Numbers (java)