题目描述:找到所有满足要求的组合,且不能重复,答案不重复,每个组合数字不重复。

题目链接:Leetcode 216. Combination Sum III

思路:深度优先搜索,列出所有组合。(没有超时)利用排序来去重。

代码如下:

class Solution:
    def combinationSum3(self, k, n):
        """
        :type k: int
        :type n: int
        :rtype: List[List[int]]
        """
        ans = []
        self.dfs(ans,[],k,n)
        return ans
        
    def dfs(self,ans,tmp,k,target):
        if len(tmp)==k and sum(tmp)==target:
            tmp.sort()
            if tmp not in ans:
                ans.append(tmp)
            return
        if len(tmp) > k:
            return 
            
        for i in range(1,10):
            if i not in tmp:
                self.dfs(ans,tmp+[i],k,target)

改进后的版本:

class Solution:
    def combinationSum3(self, k, n):
        """
        :type k: int
        :type n: int
        :rtype: List[List[int]]
        """
        ans = []
        self.dfs(ans,[],k,1,n)
        return ans
        
    def dfs(self,ans,tmp,k,start,target):
        if len(tmp)==k and target==0:
            ans.append(list(tmp))  #终点在分配单一内存
            return
        if len(tmp) > k:
            return 
            
        for i in range(start,10):
            tmp.append(i)  #进去又出来
            self.dfs(ans,tmp,k,i+1,target-i)
            tmp.pop()
            

参考资料

Java深度优先搜索利用了一个下标start达到去重目的
达到终点条件的时候,对tmp重新建立一个新内存列表,然后不断回溯。

Java的DFS:

 public List<List<Integer>> combinationSum3(int k, int n) {
    List<List<Integer>> ans = new ArrayList<>();
    combination(ans, new ArrayList<Integer>(), k, 1, n);
    return ans;
}

private void combination(List<List<Integer>> ans, List<Integer> comb, int k,  int start, int n) {
	if (comb.size() == k && n == 0) {
		List<Integer> li = new ArrayList<Integer>(comb);
		ans.add(li);
		return;
	}
	for (int i = start; i <= 9; i++) {
		comb.add(i);
		combination(ans, comb, k, i+1, n-i);
		comb.remove(comb.size() - 1);
	}
}

Leetcode 216. Combination Sum III

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-03-06
  • 2021-07-15
  • 2021-12-31
  • 2021-12-28
猜你喜欢
  • 2021-06-21
  • 2021-12-24
  • 2022-12-23
  • 2022-12-23
  • 2022-01-09
  • 2021-12-08
相关资源
相似解决方案