mirror of
https://github.com/krahets/hello-algo.git
synced 2026-04-10 14:20:43 +08:00
build
This commit is contained in:
@@ -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"
|
||||
|
||||
Reference in New Issue
Block a user