Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save adamgarcia4/8230e95960f350ac1f21ac4a00932163 to your computer and use it in GitHub Desktop.
Save adamgarcia4/8230e95960f350ac1f21ac4a00932163 to your computer and use it in GitHub Desktop.
Leetcode: Permutations i
class Solution:
# 'i' is the choice for nums[i].
# partialSolution: []
def getSolution(self, partialSolution, nums):
res = []
for idx, num in enumerate(nums):
if partialSolution[idx] == 1:
res.append(num)
return res
def backtrack(self, idx, nums, partialSolution, result):
if idx == len(nums):
result.append(self.getSolution(partialSolution, nums))
return
# Choice 1: Include (1) the element or exclude (0).
for choice in range(2):
partialSolution[idx] = choice
self.backtrack(idx + 1, nums, partialSolution, result)
def subsets(self, nums: List[int]) -> List[List[int]]:
result = []
self.backtrack(0, nums, [0] * len(nums), result)
return result
class Solution:
# 'i' is the choice for nums[i].
# partialSolution: []
def getSolution(self, partialSolution, nums):
res = []
for idx, num in enumerate(nums):
if partialSolution[idx] == 1:
res.append(num)
return res
def backtrack(self, nums, partialSolution, result):
# Goal (Base Case). I have made 'n' choices
if len(partialSolution) == len(nums):
result.append(self.getSolution(partialSolution, nums))
# Partial solution is a complete solution.
return
# partialSolution: [{0,1}] * len(nums)
# Choices -->
# BF is a boolean function. BF(partialSolution, state in this problem) -> bool.
# If a BF returns True, partialSolution is PROMISED to be valid.
# If a BF returns False, this partialSolution is invalid. Stop exploring.
# You can apply the BF:
# BEFORE placing.
# Is board able to place a queen.
# AFTER placing.
# After making a choice, check to see if this choice works.
# All depends on the problem and what is easier.
# If I can make a choice independently of previous choices, then no BF.
# Choice 1: Include the element.
partialSolution.append(1)
self.backtrack(nums, partialSolution, result)
partialSolution.pop()
# Choice 2: Don't include the element
partialSolution.append(0)
self.backtrack(nums, partialSolution, result)
partialSolution.pop()
# [1,2,3]
# [0,1,0] -> {2}
def subsets(self, nums: List[int]) -> List[List[int]]:
result = []
self.backtrack(nums, [], result)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment