Cindy's Blog

アマゾンで働いているエンジニアの日常

LeetCode 46. permutation

https://leetcode.com/problems/permutations/submissions/

find first element game !
//[1,2,3]
// 1 -> 2 -> 3
// -> 3 -> 2
// visited or not visited?
// 2 -> 3 -> 1
// 1 -> 3
// 3 -> ...

class Solution {
    public List<List<Integer>> permute(int[] nums) {        
        List<List<Integer>> answer = new ArrayList<>();
        List<Integer> current = new ArrayList<>();
        boolean[] visited = new boolean[nums.length];
        findPermutation(nums, current, visited, answer);
        
        return answer;
    }
    
    private void findPermutation(int[] nums, List<Integer> current, boolean[] visited, List<List<Integer>> answer){
        //found one of the answer
        if (current.size() == nums.length){
            answer.add(new ArrayList<>(current));//deep copy
            return;
        }
        //find first element
        for (int i = 0; i < nums.length; i++){
            if (visited[i] == true){
                continue;
            }
            
            current.add(nums[i]);
            visited[i] = true;
            findPermutation(nums, current, visited, answer);
            //back tracking
            current.remove(current.size() - 1);
            visited[i] = false;
        }
    }
}