/** * 46. Permutations * https://leetcode.com/problems/permutations/description/ * Given a collection of distinct integers, return all possible permutations. Example: Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ] * */ class Solution { val result = ArrayList<List<Int>>() var userd: BooleanArray? = null //dfs+backtracking fun permute(nums: IntArray): List<List<Int>> { val cur = ArrayList<Int>() userd = BooleanArray(nums.size) dfs(0, cur, nums) return result } fun dfs(n: Int, cur: ArrayList<Int>, nums: IntArray) { if (n == nums.size) { val temp = ArrayList<Int>() temp.addAll(cur) result.add(temp) return } for (i in 0 until nums.size) { if (userd!![i]) { continue } userd!![i] = true cur.add(nums[i]) dfs(n + 1, cur, nums) cur.removeAt(cur.size - 1)// as cur pop() userd!![i] = false } } }