leetcode 39. Combination Sum

Posted clnsx

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 39. Combination Sum相关的知识,希望对你有一定的参考价值。

题目内容

Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Example:
Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
  [7],
  [2,2,3]
]
Example 2:

Input: candidates = [2,3,5], target = 8,
A solution set is:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

分析过程

  • 题目归类:
    删除类型,在处理后需要删除值的问题。
  • 题目分析:

  • 边界分析:
    • 空值分析
    • 循环边界分析
  • 方法分析:
    • 数据结构分析
    • 状态机
    • 状态转移方程
    • 最优解
  • 测试用例构建

代码实现


import java.util.*;
class Solution {
    List<List<Integer>> list = new ArrayList<>();
    List<Integer> arraylist = new ArrayList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        return Sum(candidates,target,0);
    }
    List<List<Integer>> Sum(int[] candidates, int target,int s) {
        
        if(target <0)
            return list;
        if(target == 0){
            ArrayList<Integer> k = new ArrayList<>(arraylist);
            Collections.sort(k);
            if(!list.contains(k)){
                list.add(new ArrayList<Integer>(k));
            }
            return list;
        }
        
        if(candidates[0]>target){
            return list;
        }
        
        for(int i = s; i < candidates.length; i++) {
            arraylist.add(candidates[i]);
            Sum(candidates,target-candidates[i],i);
            arraylist.remove(arraylist.size()-1);
        }
        
        return list;
    }
}

效率提高

拓展问题

以上是关于leetcode 39. Combination Sum的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode题意分析&解答39. Combination Sum

Leetcode 39. Combination Sum

[leetcode-39-Combination Sum]

leetcode 39. Combination Sum

[array] leetcode - 39. Combination Sum - Medium

LeetCode39Combination Sum