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 b353018

Browse files
committed
添加 0090.子集II.md Scala版本
1 parent ccfb805 commit b353018

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

‎problems/0090.子集II.md‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -434,6 +434,63 @@ func subsetsWithDup(_ nums: [Int]) -> [[Int]] {
434434
}
435435
```
436436

437+
### Scala
438+
439+
不使用userd数组:
440+
441+
```scala
442+
object Solution {
443+
import scala.collection.mutable
444+
def subsetsWithDup(nums: Array[Int]): List[List[Int]] = {
445+
var result = mutable.ListBuffer[List[Int]]()
446+
var path = mutable.ListBuffer[Int]()
447+
var num = nums.sorted // 排序
448+
449+
def backtracking(startIndex: Int): Unit = {
450+
result.append(path.toList)
451+
if (startIndex >= num.size){
452+
return
453+
}
454+
for (i <- startIndex until num.size) {
455+
// 同一树层重复的元素不进入回溯
456+
if (!(i > startIndex && num(i) == num(i - 1))) {
457+
path.append(num(i))
458+
backtracking(i + 1)
459+
path.remove(path.size - 1)
460+
}
461+
}
462+
}
463+
464+
backtracking(0)
465+
result.toList
466+
}
467+
}
468+
```
469+
470+
使用Set去重:
471+
```scala
472+
object Solution {
473+
import scala.collection.mutable
474+
def subsetsWithDup(nums: Array[Int]): List[List[Int]] = {
475+
var result = mutable.Set[List[Int]]()
476+
var num = nums.sorted
477+
def backtracking(path: mutable.ListBuffer[Int], startIndex: Int): Unit = {
478+
if (startIndex == num.length) {
479+
result.add(path.toList)
480+
return
481+
}
482+
path.append(num(startIndex))
483+
backtracking(path, startIndex + 1) // 选择
484+
path.remove(path.size - 1)
485+
backtracking(path, startIndex + 1) // 不选择
486+
}
487+
488+
backtracking(mutable.ListBuffer[Int](), 0)
489+
490+
result.toList
491+
}
492+
}
493+
```
437494

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

0 commit comments

Comments
(0)

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