来源:力扣每日一题 2022/2/28
https://leetcode-cn.com/problems/maximum-number-of-achievable-transfer-requests/
/**
* @param {number} n
* @param {number[][]} requests
* @return {number}
*/
var maximumRequests = function(n, requests) {
let result=0;
let balance=new Array(n).fill(0)
let counts=0
let balanced=n
function dfs(requests,pos){
if(pos===requests.length){
if(balanced===n){
result=Math.max(result,counts)
}
return
}
//假设不包括本项
dfs(requests,pos+1)
//包括
//为回溯预留值
let b=balanced
counts++
//输入改变值
let [from,to]=requests[pos]
//若之前是平衡的,则现在变为不平衡
balanced-=balance[from]===0?1:0
balanced-=balance[to]===0?1:0
balance[from]++
balance[to]--
//检测现在还平衡吗
balanced+=balance[to]===0?1:0
balanced+=balance[from]===0?1:0
//对下一项进行搜索
dfs(requests,pos+1)
//回溯
balance[from]--
balance[to]++
balanced=b
counts--
}
dfs(requests,0)
return result
};
磕磕绊绊抄答案写完的。。
这也算迭代的一种吧
回溯算法模板?:
现在还不大熟练。以后再说吧
Comments | NOTHING