当前位置: 首页 > news >正文

Lintcode 135 · 数字组合【中的 排列组合问题 DFS Java】

题目

在这里插入图片描述
题目链接: https://www.lintcode.com/problem/135

思路

经典的组合问题:
需要注意的是:需要去重,因为题目要求unique combinations
需要提前排序,因为题目要求结果输出ascending order
注意递归的出口
每个数字可以重复用,所以startIndex传入下一层递归时不加1

Java代码

public class Solution {/*** @param candidates: A list of integers* @param target: An integer* @return: A list of lists of integers*          we will sort your return value in output*/public List<List<Integer>> combinationSum(int[] candidates, int target) {List<List<Integer>> ans = new ArrayList<>();Set<String>  visited = new HashSet<>();List<Integer> path = new ArrayList<>();Arrays.sort(candidates);dfs(candidates,0,0,target,path,visited,ans);return ans;}public void dfs(int[] arr,int idx,int sum,int target,List<Integer> path,Set<String> visited,List<List<Integer>> ans){if(sum> target) return;if(sum == target){if(visited.contains(path.toString()))return;ans.add(new ArrayList<>(path));visited.add(path.toString());}else{for (int i = idx; i <arr.length; i++) {path.add(arr[i]);dfs(arr,i,sum+arr[i],target,path,visited,ans);path.remove(path.size()-1);  //恢复现场}}}}

http://www.mrgr.cn/news/52648.html

相关文章:

  • 植物大战僵尸杂交版即将新增内容介绍
  • 【每日一题】LeetCode每日一题-无重复字符的最长子串
  • 浅谈es6箭头函数
  • 碳酸二辛酯行业分析:未来几年年复合增长率CAGR为3.37%
  • 【前端】Matter:过滤与高级碰撞检测
  • ssm基于SSM的社区管理系统+vue
  • 10秒钟用Midjourney画出国风味的变形金刚
  • VS Code对齐NoteBook和Terminal的Python环境
  • 【ICPC】The 2021 CCPC Guilin Onsite (XXII Open Cup, Grand Prix of EDG) D
  • 速盾:cdn有防御吗?
  • 动态规划(1)斐波那契数列模型
  • mysql--索引
  • Hi3061M——VL53L0X激光测距(IIC)(同样适用于其他MCU)
  • JAVA八股
  • ts 中 type 和 interface 的区别
  • 【vivado】vivado联合modelsim仿真
  • VUE组件间的通信方式都有哪些
  • MySQL 免密登录的几种配置方式
  • CTFHub | HTTP协议 - 请求方式 | 题解实操
  • rollup.js 插件实现原理与自定义