leetcode.com/problems/permutations/
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> answer = new ArrayList<List<Integer>>();
helper(0, nums, answer);
return answer;
}
private void helper(int start, int[] nums, List<List<Integer>> answer) {
if (start == nums.length - 1) {
List<Integer> list = new ArrayList<Integer>();
for (int num : nums) {
list.add(num);
}
answer.add(list);
return;
}
for (int i = start; i < nums.length; i++) {
swap(nums, i, start);
helper(start + 1, nums, answer);
swap(nums, i, start);
}
}
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
'개발자 > algorithm' 카테고리의 다른 글
LeetCode, Valid Parentheses (Java) (0) | 2021.01.09 |
---|---|
LeetCode, Rotate Image (Java) (0) | 2021.01.08 |
LeetCode, Maximum Subarray (Java) (0) | 2021.01.06 |
LeetCode, Climbing Stairs (Java) (0) | 2021.01.05 |
LeetCode, Best Time to Buy and Sell Stock (Java) (0) | 2021.01.05 |