アプローチ
- Backtracking
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
helper(new ArrayList<>(), new boolean[nums.length], nums, result);
return result;
}
public void helper(ArrayList<Integer> arrayList, boolean[] isVisited, int[] nums, List<List<Integer>> result) {
if (arrayList.size() == nums.length) {
result.add(new ArrayList<>(arrayList));
return;
}
for (int i = 0; i < nums.length; i++) {
if (isVisited[i]) {
continue;
}
isVisited[i] = true;
arrayList.add(nums[i]);
helper(arrayList, isVisited, nums, result);
isVisited[i] = false;
arrayList.remove(arrayList.size() - 1);
// arrayListの最後を要素を削除し、次の数値が入れられるようにする
}
}
}
下記の動画を参考にしました