46. Permutations & 47. PermutationsII

 46Permutations https://leetcode.com/problems/permutations/

遞迴代入深度

深度 = 長度  將目前解加入解集合中
若沒有則把目前解往下遞迴 深度+1
頭開始選,選過的item不能再選(需要紀錄)
每次遞迴完後把最後一個元素拿出來繼續選下一個
Python append solution 需要先做 slice 以免變成 copy by addr

P(n, d)
perm(items, d, n, cur, ans)
    if d == n:
        ans.append(cur[:])
        return
    for i: 0 to len(items)
        used[i] = True
        cur.append(items[i])
        perm(items, d+1, n, cur, ans)
        cur.pop()
        used[i] = False

47 需排除已存在解,

1. 直接方式:if not cur in ans: ans.append(cur[:])

2. 在迴圈時就排除

last = -11 # 請設定在 constraint 以外

if items[i] == last: continue

last = cur.pop()

留言

這個網誌中的熱門文章

38. Count and Say