leetcode 40. Combination Sum II

题目内容

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

Each number in candidates may only be used once in the combination.

Note:

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

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

分析过程

  • 题目归类:
    使用后删除类题目
  • 题目分析:
    递归处理使用后删除即可。掌握方法就很简单
  • 边界分析:
    • 空值分析
    • 循环边界分析
  • 方法分析:
    • 数据结构分析
    • 状态机
    • 状态转移方程
    • 最优解
  • 测试用例构建

代码实现

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

效率提高

拓展问题

posted @ 2020-02-20 12:56  clnsx  阅读(89)  评论(0编辑  收藏  举报