[LeetCode][Java] Combination Sum

來源:互聯網
上載者:User

標籤:leetcode   java   combination sum   

題目:

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

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

Note:
  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.

For example, given candidate set 2,3,6,7 and target 7
A solution set is: 
[7] 
[2, 2, 3] 


題意:

給定一組整數(C)和一個目標值 (T),從(C)中找出所有的存在且唯一的組合,使他們的和等於(T)。

同一個重複數字可以在C無限次的選擇。 

注意:

     1.所有的數字包括目標值都是非負整數.

     2. 組合中的元素(a1, a2, … , ak)為升序排列。(ie, a1 ≤ a2 ≤ … ≤ ak).

     3.最終的解中組合不能出現重複.

比如,給定一組整數集2,3,6,7 和目標值7

一個解集為:

[7] 
[2, 2, 3] .

演算法分析:

該題是一個求解迴圈子問題的題目,採用遞迴進行深度優先搜尋。基本思路是先排好序,然後每次遞迴中把剩下的元素一一加到結果集合中,並且把目標減去加入的元素,然後把剩下元素(包括當前加入的元素)放到下一層遞迴中解決子問題。演算法複雜度因為是NP問題,所以自然是指數量級的。

AC代碼:

/** *  The first impression of this problem should be depth-first search(DFS). To solve DFS problem, recursion is a normal implementation. *  Note that the candidates array is not sorted, we need to sort it first.  */public class Solution {    List<List<Integer>> result;List<Integer> solu;public List<List<Integer>> combinationSum(int[] candidates, int target) {        result = new ArrayList<>();        solu = new ArrayList<>();        if(candidates == null || candidates.length == 0) return result;        Arrays.sort(candidates);        getCombination(candidates, target, 0, 0);        return result;    }public void getCombination(int[] candidates, int target, int sum, int level){if(sum>target) return;if(sum==target){result.add(new ArrayList<>(solu));return;}for(int i=level;i<candidates.length;i++){sum+=candidates[i];solu.add(candidates[i]);getCombination(candidates, target, sum, i);solu.remove(solu.size()-1);sum-=candidates[i];}}}



著作權聲明:本文為博主原創文章,轉載註明出處

[LeetCode][Java] Combination Sum

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.