August 2, 2023

LeetCode permutations (ChatGPT)

Решал задачу на 46. Permutations. Одно решение - на котлине двухгодичной давности, второе - сегодня на Java, третье - я скормил второе решение ChatGPT 3.5 и он его оптимизировал. Мне показалось, что он хорош в популярных алгоритмических задачах, которые гуглятся, он улучшил мое решение с двух миллисекунд до одной миллисекунды.

Мое решение (https://gist.github.com/Manjago/175c7b33cfb0dfad2215484309c3c89b):

Мое решение, улучшенное ChatGPT (https://gist.github.com/Manjago/cc6e18d6b4aa63c5aad16ede1ce54f0d):

ChatGPT выдал прекрасное объяснение:

Optimizations made in the code:

  1. Eliminate the need for copying arrays: The original code uses an array called nextNums to store the remaining elements after excluding the current element from the permutation. This requires copying elements in each iteration, which can be avoided by using a boolean array used to track whether an element has been used or not.
  2. Use List<> interface for input and output: Instead of using a primitive array as input, the method now takes a List<> as input, making it more flexible and easier to use. Similarly, the output is also a List<List<Integer>> to make it easier to store and manipulate the permutations.
  3. Simplify base case handling: The original code has a specific case for an array of length 1. This is now handled implicitly in the recursive function by checking if the size of the current list matches the length of the original array.

With these optimizations, the code will be more efficient and easier to understand. It generates all permutations of the input array without creating unnecessary copies and improves overall readability.

Я все-таки чуть попытаюсь оправдаться за свое решение - я изображал, как будто я прохожу интервью и писал код в редакторе LeetCode, он все-таки гораздо менее мне привычен, в итоге выбрал решение "в лоб"