leetcode刷題筆記四十六 全排列
阿新 • • 發佈:2020-07-03
leetcode刷題筆記四十六 全排列
源地址:46. 全排列
問題描述:
給定一個 沒有重複 數字的序列,返回其所有可能的全排列。
示例:
輸入: [1,2,3]
輸出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
程式碼補充:
//結合DFS與回溯法 //res => 儲存排列結果 //path => 記錄單次遍歷的路徑 //used => 記錄本次遍歷使用過的節點 //全排列過程實際是進行一次深度遍歷的過程 //length => 目標長度,構成排列的高度 //depth => 目前遍歷的層次,樹高 import scala.collection.mutable object Solution { def permute(nums: Array[Int]): List[List[Int]] = { val length = nums.length if (length == 0) return List() var res = mutable.ListBuffer[List[Int]]() var path = mutable.ListBuffer[Int]() var used = mutable.Set.empty[Int] dfs(nums, length, 0, path, used, res) return res.toList } def dfs(nums:Array[Int], length:Int, depth:Int, path:mutable.ListBuffer[Int], used:mutable.Set[Int], res:mutable.ListBuffer[List[Int]]) : Unit = { //完成一次遍歷,將結果保存於res中,返回 if (depth == length) { res += (path.toList) return } for(i <- nums.indices){ //當前結果尚未遍歷 if(used.contains(nums(i)) == false){ //路徑更新,使用節點更新 path += nums(i) used += nums(i) //接著遍歷下一個未訪問過的節點 dfs(nums, length, depth+1, path, used, res) //回溯 path -= nums(i) used -= nums(i) } } } }