| 5 | } |
| 6 | |
| 7 | fun backtrack(i: Int, currSubset: MutableList<Int>, nums: List<Int>, res: MutableList<List<Int>>) { |
| 8 | // Base case: if all elements have been considered, add the |
| 9 | // current subset to the output. |
| 10 | if (i == nums.size) { |
| 11 | res.add(currSubset.toList()) |
| 12 | return |
| 13 | } |
| 14 | // Include the current element and recursively explore all paths |
| 15 | // that branch from this subset. |
| 16 | currSubset.add(nums[i]) |
| 17 | backtrack(i + 1, currSubset, nums, res) |
| 18 | // Exclude the current element and recursively explore all paths |
| 19 | // that branch from this subset. |
| 20 | currSubset.removeAt(currSubset.size - 1) |
| 21 | backtrack(i + 1, currSubset, nums, res) |
| 22 | } |