iT邦幫忙

2022 iThome 鐵人賽

DAY 25
1
自我挑戰組

LeetCode Top 100 Liked系列 第 25

[Day 25] Permutations (Medium)

  • 分享至 

  • xImage
  •  

46. Permutations

Question

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

Example 1

Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

Solution 1: DFS

class Solution:
    def __init__(self):
        self.ans = []
        
    def dfs(self, restPermu: List[int], prevPermu: List[int]) -> None:
        if not restPermu:
            self.ans.append(prevPermu)
        for i in range(len(restPermu)):
            self.dfs(restPermu[:i] + restPermu[i+1:], prevPermu + [restPermu[i]])
        
    def permute(self, nums: List[int]) -> List[List[int]]:
        self.dfs(nums, [])
        return self.ans

Time Complexity: O(N!)
Space Complexity: O(1)

Reference

https://leetcode.com/problems/permutations/discuss/18296/Simple-Python-solution-(DFS).
https://blog.csdn.net/Jacky_chenjp/article/details/66477538

Follow-up: 47. Permutations II

Follow-up: 60. Permutation Sequence

31. Next Permutation


上一篇
[Day 24] Search in Rotated Sorted Array (Medium)
下一篇
[Day 26] Symmetric Tree (Easy)
系列文
LeetCode Top 100 Liked77
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言