Iam_Sandeep

40. Combination Sum II

Jul 12th, 2022 (edited)
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.63 KB | None | 0 0
  1. Iterative logic to remove duplicates
  2. class Solution:
  3.     def combinationSum2(self, A: List[int], tar: int) -> List[List[int]]:
  4.         A.sort(reverse=True)
  5.         st=[]
  6.         ans=[]
  7.         n=len(A)
  8.         def dfs(i,x):
  9.             if x==tar:
  10.                 ans.append(st[:])
  11.             if x>=tar:
  12.                 return
  13.             prev=float('inf')
  14.             for j in range(i,n):
  15.                 if A[j]!=prev:#Avoiding duplicate step here
  16.                     st.append(A[j])
  17.                     dfs(j+1,x+A[j])
  18.                     st.pop()
  19.                 prev=A[j]
  20.        
  21.         dfs(0,0)
  22.         return ans
Add Comment
Please, Sign In to add comment