반응형
Leetcode - Permutations
설명
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Example:
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
제한사항
- 1 <= nums.length <= 6
- -10 <= nums[i] <= 10
- All the integers of nums are unique.
소스코드
import java.util.List;
import java.util.ArrayList;
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> answer = new ArrayList<List<Integer>>();
int depth = 0;
permutation(nums, depth, answer);
return answer;
}
private void permutation(int[] nums, int depth, List<List<Integer>> answer) {
if(depth == nums.length - 1) {
List<Integer> temp = new ArrayList<>();
for(int item : nums) {
temp.add(item);
}
answer.add(temp);
return;
}
for(int i=depth; i<nums.length; i++) {
swap(nums, depth, i);
permutation(nums, depth + 1, answer);
swap(nums, depth, i);
}
}
private void swap(int[] nums, int depth, int i) {
int temp = nums[depth];
nums[depth] = nums[i];
nums[i] = temp;
}
}
반응형