Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 97fc88e

Browse files
committed
添加 0046.全排列.md Scala版本
1 parent 87abfa1 commit 97fc88e

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

‎problems/0046.全排列.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -456,6 +456,36 @@ func permute(_ nums: [Int]) -> [[Int]] {
456456
}
457457
```
458458

459+
### Scala
460+
461+
```scala
462+
object Solution {
463+
import scala.collection.mutable
464+
def permute(nums: Array[Int]): List[List[Int]] = {
465+
var result = mutable.ListBuffer[List[Int]]()
466+
var path = mutable.ListBuffer[Int]()
467+
468+
def backtracking(used: Array[Boolean]): Unit = {
469+
if (path.size == nums.size) {
470+
// 如果path的长度和nums相等,那么可以添加到结果集
471+
result.append(path.toList)
472+
return
473+
}
474+
// 添加循环守卫,只有当当前数字没有用过的情况下才进入回溯
475+
for (i <- nums.indices if used(i) == false) {
476+
used(i) = true
477+
path.append(nums(i))
478+
backtracking(used) // 回溯
479+
path.remove(path.size - 1)
480+
used(i) = false
481+
}
482+
}
483+
484+
backtracking(new Array[Boolean](nums.size)) // 调用方法
485+
result.toList // 最终返回结果集的List形式
486+
}
487+
}
488+
```
459489

460490
-----------------------
461491
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /