2019年11月22日 星期五

[LeetCode] 77. Combinations

題目:
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

Example:
Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]
思路:
用遞迴的方式, 從後面排回來
12
13
   -> 23
14
   -> 24
   -> 34

n = 4, k = 3
123
124
   -> 134
           -> 234

https://gist.github.com/richardneko/6870d498e3916733728917b0d9c8ba7f






[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

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