This commit is contained in:
krahets
2024-05-24 16:12:17 +08:00
parent e434a3343c
commit 6bac0db1c4
22 changed files with 635 additions and 99 deletions
@@ -506,9 +506,36 @@ comments: true
=== "Ruby"
```ruby title="permutations_i.rb"
[class]{}-[func]{backtrack}
### 回溯演算法:全排列 I ###
def backtrack(state, choices, selected, res)
# 當狀態長度等於元素數量時,記錄解
if state.length == choices.length
res << state.dup
return
end
[class]{}-[func]{permutations_i}
# 走訪所有選擇
choices.each_with_index do |choice, i|
# 剪枝:不允許重複選擇元素
unless selected[i]
# 嘗試:做出選擇,更新狀態
selected[i] = true
state << choice
# 進行下一輪選擇
backtrack(state, choices, selected, res)
# 回退:撤銷選擇,恢復到之前的狀態
selected[i] = false
state.pop
end
end
end
### 全排列 I ###
def permutations_i(nums)
res = []
backtrack([], nums, Array.new(nums.length, false), res)
res
end
```
=== "Zig"
@@ -1032,9 +1059,38 @@ comments: true
=== "Ruby"
```ruby title="permutations_ii.rb"
[class]{}-[func]{backtrack}
### 回溯演算法:全排列 II ###
def backtrack(state, choices, selected, res)
# 當狀態長度等於元素數量時,記錄解
if state.length == choices.length
res << state.dup
return
end
[class]{}-[func]{permutations_ii}
# 走訪所有選擇
duplicated = Set.new
choices.each_with_index do |choice, i|
# 剪枝:不允許重複選擇元素 且 不允許重複選擇相等元素
if !selected[i] && !duplicated.include?(choice)
# 嘗試:做出選擇,更新狀態
duplicated.add(choice)
selected[i] = true
state << choice
# 進行下一輪選擇
backtrack(state, choices, selected, res)
# 回退:撤銷選擇,恢復到之前的狀態
selected[i] = false
state.pop
end
end
end
### 全排列 II ###
def permutations_ii(nums)
res = []
backtrack([], nums, Array.new(nums.length, false), res)
res
end
```
=== "Zig"