46. Permutations

45次阅读

共计 828 个字符,预计需要花费 3 分钟才能阅读完成。

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]
]

难度:medium
题目:给定一组集合元素,返回其所有排列数。
思路:递归
Runtime: 3 ms, faster than 70.98% of Java online submissions for Permutations.Memory Usage: 28 MB, less than 4.36% of Java online submissions for Permutations.
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
permute(nums, 0, new Stack<Integer>(), result);

return result;
}

private void permute(int[] nums, int idx, Stack<Integer> stack, List<List<Integer>> result) {
if (idx == nums.length) {
result.add(new ArrayList<>(stack));
return;
}

for (int i = idx; i < nums.length; i++) {
stack.push(nums[i]);
swap(nums, i, idx);
permute(nums, idx + 1, stack, result);
swap(nums, i, idx);
stack.pop();
}
}

private void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
}

正文完
 0