[LeetCode] 46. Permutations

donghyeok·2021년 11월 28일
0

알고리즘 문제풀이

목록 보기
5/144

문제 설명

문제 풀이

  • Permutation을 recursive하게 구현하였다.

소스 코드 (JAVA)

class Solution {
    public boolean[] chk;
    public List<List<Integer>> result;
    
    public List<List<Integer>> permute(int[] nums) {
        chk = new boolean[nums.length];
        result = new ArrayList<>();
        List<Integer> temp = new ArrayList<>();
        permutations(nums, temp, 0);
        return result;
    }
    
    public void permutations(int[] nums, List<Integer> temp, int ind) {
        if (ind == nums.length) {
            result.add(new ArrayList(temp));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (chk[i] == true) continue;
            chk[i] = true;
            temp.add(nums[i]);
            permutations(nums, temp, ind + 1);
            temp.remove(temp.size() - 1);
            chk[i] = false;
        }
    }
}

0개의 댓글