0
0

More than 1 year has passed since last update.

Leetcode 46. Permutations

Posted at

アプローチ

  • 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の最後を要素を削除し、次の数値が入れられるようにする            
        }
    }
}

下記の動画を参考にしました

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0