於leetcode.46 Permutations
想請問為甚麼在其中的For迴圈裡呼叫backtrace
後面的pop到底是造成了甚麼條件才會觸發呢?
是因為滿足了前兩個條件才觸發POP的嗎?
麻煩大大幫忙
class Solution(object):
def permute(self, nums):
result = []
path = []
def backtrace(nums, index):
if len(path) > len(nums):
return
if len(path) == len(nums):
result.append(path[:])
return
for i in range(index, len(nums)):
if nums[i] in path:
continue
path.append(nums[i])
backtrace(nums, 0)
path.pop()
backtrace(nums, 0)
return result
function遇到return就會結束這個function:
class Solution(object):
def permute(self, nums):
result = []
path = []
def backtrace(nums, index):
if len(path) > len(nums):
return #跳出backtrace
if len(path) == len(nums):
result.append(path[:])
return #跳出backtrace
for i in range(index, len(nums)):
if nums[i] in path:
continue #跳過一次迴圈執行
path.append(nums[i])
backtrace(nums, 0)
path.pop()
backtrace(nums, 0)
return result
if len(path) > len(nums):
if len(path) == len(nums):
這兩個條件滿足任一都會,並且第一個優先
不滿足這兩個條件的都會執行下面的for
然後if nums[i] in path:
會跳過一次執行。
附帶一提,我個人比較愛這樣寫
for i in range(index, len(nums)):
if nums[i] not in path:
path.append(nums[i])
backtrace(nums, 0)
path.pop()