python通过参考不起作用是什么?
我有一个解决数组排列的解决方案,如下所示:
class Solution:
def permuteHelper(self,li,nums,ji,x):
if len(ji)==x:
li.append(ji)
return
for i in range(len(nums)):
ji.append(nums[i])
self.permuteHelper(li,nums[:i]+nums[i+1:],ji,x)
ji.pop()
def permute(self, nums: List[int]) -> List[List[int]]:
li = []
ji = []
self.permuteHelper(li,nums,ji,len(nums))
return li
想法是使用另一个数组,该数组在附加的元素之前先跳过原始数组中的每个元素。但是,这样做时,我将获得空列表列表的输出。
在线我看到有人这样做了,除了他们这样做:
class Solution:
def permuteHelper(self,li,nums,ji,x):
if len(ji)==x:
li.append(ji)
return
for i in range(len(nums)):
self.permuteHelper(li,nums[:i]+nums[i+1:],ji+[nums[i]],x)
def permute(self, nums: List[int]) -> List[List[int]]:
li = []
ji = []
self.permuteHelper(li,nums,ji,len(nums))
return li
我不知道他们的解决方案为何奏效,而我的解决方案也没有,我的逻辑与他们的逻辑相同,但我不明白差异。有人可以解释为什么第二个工作而第一个效果不起?
I have a solution for generating permutations of an array which is as follows:
class Solution:
def permuteHelper(self,li,nums,ji,x):
if len(ji)==x:
li.append(ji)
return
for i in range(len(nums)):
ji.append(nums[i])
self.permuteHelper(li,nums[:i]+nums[i+1:],ji,x)
ji.pop()
def permute(self, nums: List[int]) -> List[List[int]]:
li = []
ji = []
self.permuteHelper(li,nums,ji,len(nums))
return li
Idea is to use another array that appends each element from original array one by one skipping before appended elements. But when doing it like this, I am getting an output of list of empty lists.
Online I saw someone do the same except they did it like this:
class Solution:
def permuteHelper(self,li,nums,ji,x):
if len(ji)==x:
li.append(ji)
return
for i in range(len(nums)):
self.permuteHelper(li,nums[:i]+nums[i+1:],ji+[nums[i]],x)
def permute(self, nums: List[int]) -> List[List[int]]:
li = []
ji = []
self.permuteHelper(li,nums,ji,len(nums))
return li
I have no idea why their solution worked and mine did not, I had the same logic as theirs but I don't understand the difference. Can someone please explain why the second one worked and the first one did not?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论