Problems where you can imagine the solution space as a tree, here's an example for Tic Tac Toe
https://www.hackerrank.com/contests/buacm/challenges/cheap-paint
from copy import deepcopy
def solve(prices, used):
if len(prices) == 1:
for i in range(len(prices[0])):
if i not in used:
return prices[0][i]
vals = []
for i in range(len(prices[0])):
if i not in used:
usedcpy = deepcopy(used)
usedcpy.add(i)
vals.append(prices[0][i] + solve(prices[1:], usedcpy))
return min(vals)
num = int(input())
data = []
for i in range(num):
data.append(list(map(lambda x: int(x), input().split())))
print(solve(data, set()))
In 3 1 2 3 3 2 1 3 3 1
Out 4
Problem: Find the minimum sum obtainable by taking 1 value from each row but no two values can be from the same column
for each new possible 'move'
copy current state
apply new 'move'
recursively call solution
for each new possible 'move'
apply new 'move'
recursively call solution
unapply the 'move'
Two options, make a bunch of copies of our state, or use the same state in every recursive call
for each new possible 'move'
copy current state
apply new 'move'
recursively call solution
In this algorithm we copy our entire state, we'll assume state is some sort of list since that is generally the case
void backtrack(vector<int> state){
for(int i = 0; i < state.size(); i++){
vector<int> state_copy = state;
//state gets copied here ^^^^^
modify_state(state_copy[i]);
backtrack(state_copy);
}
}
from copy import deepcopy
def backtrack(state):
for i in range(len(state))
state_copy = deepcopy(state)
#state gets copied here ^^^^^
modify_state(state_copy[i])
backtrack(state_copy)
C++ Example
Python Example
https://leetcode.com/problems/binary-watch/
https://leetcode.com/problems/permutations/
class Solution(object):
def permute(self, nums):
results = []
self.helper(nums, [], results)
return results
def helper(self, nums, temp, results):
if len(temp) == len(nums):
results.append(temp[:])
return
for i in range(0, len(nums)):
if nums[i] not in temp:
temp.append(nums[i])
self.helper(nums, temp, results)
temp.pop()
Permutations solution
https://leetcode.com/problems/n-queens/
global solutions
solve(board)
if n queens placed
add board to solutions
return
find next square a queen can be placed on
copy board to boardcopy
place queen on boardcopy
solve(boardcopy)
if no valid square found
return
Sounds pretty simple right?
It is but the actual implementation gets messy
But that's enough confusing algorithms for now, maybe we'll go over these optimizations in more detail another time