Leetcode backtracking method four board one solution template

1 General backtracking template

Insert picture description here

vector<xxx> solution;
void backtrack(路径, 选择列表){
    
    
	if (满足终止条件) {
    
    
		添加路径(当前解);
		return;
	}
	for (选择 : 选择列表) {
    
    
		if (notValid(选择)) continue;
		做选择;     // 在选择列表中移除<选择>
		backtrack(路径, 选择列表);
		撤销选择;   // 将<选择>恢复到选择列表中
	}
}

2 Backtracking method commonly used four axes + one solution (first index + inPath + sort adjacent deduplication + set non-adjacent deduplication)

By training the classic topics, the most commonly used technique in solving the problem of backtracking main 4types, depending on the nature when solving problems through a variety can be mechanized to solving mix which , for these four tips are detailed below

Four boards and one solution Features example
inPath备忘录(i = 0) 避免重复相同的选择 Avoid [1,1,1]or [2,2,2]appear
first索引(i = first) Avoid repeating the same choice + 避免顺序不同,但组合相同的解 Avoid [1,2,3]and [1,3,2]co-occur
sort相邻去重!(input[i-1]==input[i]) 输入有重复Time, avoid repeating exactly the same solution Avoid [2,2,3]and [2,2,3]co-occur
set非相邻去重!set.count(input[i]) 输入有重复+ 不能sort, avoid repeating exactly the same solution Same as above
bool backtrack(args) {} Only return to 1个解useif (backtrack()) return true; ——

[Remarks]: Two solutions with different but identical paths[1, 2, 3, 2] can appear[2, 3]

The usage of the above four boards and one solution in different questions, the specific usage method can be directly clicked on the question link to view

Four axes Applicable scene topic
inPath备忘录(i = 0) arrangement 46. ​​Full arrangement ; 47. Full arrangement II
first索引(i = first) Combination/subset/split 77. Combination ; 39. Combination sum ; 216. Combination sum III ;
78. Subset ; 131. Split palindrome ; 93. Restore IP address
sort相邻去重!(input[i-1]==input[i]) The input is repeated (assisting the above scenario) 90. Subset II ; 40. Combination Sum II ; 47. Full Permutation II
set非相邻去重!set.count(input[i]) The input is duplicated + cannot be sorted 491. Increasing Subsequence
bool backtrack(args) {} Only returns1个解 37. Solve Sudoku ; 332. Rearrange the itinerary
Other methods Applicable scene topic
Backtracking template + multi-condition pruning Board problem etc. 51. Queen N ; 37. Solving Sudoku ; 17. Letter combination of phone number
Backtracking template + new data structure Graph theory 332. Re-arrange the itinerary (Euler circuit)

Appendix: List of Brush Questions for this Topic

Insert picture description here

Thanks

Thank you for sorting out the idea of ​​the official account of "Code Random Record". Welcome everyone to pay attention to the official account of this big guy

Guess you like

Origin blog.csdn.net/SL_World/article/details/114838833