2019年11月22日 星期五

[LeetCode] 46. Permutations

題目:
Given a collection of distinct integers, return all possible permutations.

Example:
Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
思路:
從1開始排
1

接著2可以插在1的前面或後面, 兩種排列方式
12
21

最後3可以分別插入12和21前中後的位置
12
312
132
123

21
321
231
213

https://gist.github.com/richardneko/8ec0f82967460a6c2a4bdc0740269164

僅為自己刷完題後的紀錄, 不一定是最佳解...

沒有留言:

張貼留言