使用with遞迴回溯

2021-05-23 06:16:25 字數 980 閱讀 7731

--向上回溯,查詢頂級部門

declare @pdeptid uniqueidentifier;

with dept(deptid,pdeptid)

as(select udepid,uparentid from oa.dbo.depinfo where udepid in(

select p.udepid from oa.dbo.postinfo as p

inner join oa.dbo.userinpost as up on p.upostid=up.upostid

where up.uuserid='fbdcc80d-8e1f-45b8-837b-73ecf3082477')

union all

select udepid,uparentid from oa.dbo.depinfo as di

inner join dept as d on di.udepid=d.pdeptid

where di.uparentid is not null

)select @pdeptid=a.deptid from dept as a

left join dept as b on a.pdeptid=b.deptid

where b.deptid is null;

select @pdeptid;

--向下遞迴查詢所有子部門

with dept2(deptid,pdeptid)

as(select udepid,uparentid from oa.dbo.depinfo

where udepid=@pdeptid

union all

select udepid,uparentid from oa.dbo.depinfo as di

inner join dept2 as d on di.uparentid=d.deptid

where di.isuse=1

)select * from dept2

遞迴回溯總結

遞迴回溯法對解空間樹作深度優先搜尋,一般情況可表示為 void backtrack int n else 引數n表示遞迴的深度 is ok 表示已經求得問題解 print reult 表示列印結果 如果只求出乙個可行解,那麼求得第乙個問題解後便可exit 如果要求出所有可行解則不需exit base...

遞迴回溯總結

8皇后問題是一道非常經典的題目。題目是說,乙個n n的西洋棋棋盤上主放置n個皇后,使其不能相互攻擊,即任何兩個皇后都不能處在棋盤的同一行,同一列,同一條斜線上,試問共有多少種擺法?其實,題目就是要找出所有的可能情況,然後排除其中不符合條件的情況,剩下的情況即為所要求的。怎麼找出所有的情況呢?對於8皇...

遞迴 回溯 分治

題目 給定一組不含重複元素的整數陣列 nums,返回該陣列所有可能的子集 冪集 說明 解集不能包含重複的子集。示例 輸入 nums 1,2,3 輸出 3 1 2 1,2,3 1,3 2,3 1,2 方法1 回溯法 o 2 n item.push back nums i 將nums中第i個數字push...