leetcode 組合總和II(Java)

leetcode題目

組合總和II -- leetcode 40

題目描述

給定一個數組 candidates 和一個目標數 target ,找出 candidates 
中所有可以使數字和爲 target 的組合。

candidates 中的每個數字在每個組合中只能使用一次。

說明:

所有數字(包括目標數)都是正整數。
解集不能包含重複的組合。 
示例 1:

輸入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集爲:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]
示例 2:

輸入: candidates = [2,5,2,1,2], target = 5,
所求解集爲:
[
  [1,2,2],
  [5]
]

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/combination-sum-ii
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

思路

回溯算法
需要去除本元素,和重複的元素(排序後處理)

代碼

package com.leetcode.array;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 題目: 
 * 組合總和II -- leetcode 40
 * 
 * 題目描述:
 * 
給定一個數組 candidates 和一個目標數 target ,找出 candidates 
中所有可以使數字和爲 target 的組合。

candidates 中的每個數字在每個組合中只能使用一次。

說明:

所有數字(包括目標數)都是正整數。
解集不能包含重複的組合。 
示例 1:

輸入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集爲:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]
示例 2:

輸入: candidates = [2,5,2,1,2], target = 5,
所求解集爲:
[
  [1,2,2],
  [5]
]

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/combination-sum-ii
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
 */
public class CombinationSumII {
	/**
	 * 思路: 
	 * 1、回溯算法
	 * 2、需要去除本元素,和重複的元素(排序後處理)
	 */
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        
        if (candidates == null) {
            return res;
        }
        
        Arrays.sort(candidates);
        addCombinations(candidates, 0, target, new ArrayList<Integer>(), res);
        
        return res;
    }
    
    private void addCombinations(int[] candidates, int start, int target, List<Integer> cache, List<List<Integer>> res){
        if (target < 0) {
            return;
        }
        if (target == 0) {
            res.add(new ArrayList<>(cache));
        }
        for (int i=start; i<candidates.length; i++) {
            if (candidates[i] > target) {
                return;
            }
            // 去重
            if (i>start && candidates[i] == candidates[i-1]) {
                continue;
            }
            
            cache.add(candidates[i]);
            addCombinations(candidates, i+1, target-candidates[i], cache, res);
            cache.remove(cache.size()-1);
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章