Leetcode39--->Combination Sum(在數組中找出和為target的組合)


題目: 給定一個數組candidates和一個目標值target,求出數組中相加結果為target的數字組合;

舉例:

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

[[7],[2, 2, 3]]

從舉例中可以看出,同一個數字可以使用多次,且結果是唯一的;

解題思路:

我個人感覺該題目一點也不難,其實也是一個遞歸的過程,當達到遞歸條件時,就將結果加入結果集;

首先題目沒說給的數組有啥特性,因此我先將數組進行了排序,這樣在某個點找不着結果,那后面的都比target大,自然也就沒有結果了。廢話不多說,直接看代碼;

代碼如下:

 1 import java.util.*;
 2 public class Solution {
 3     public List<List<Integer>> combinationSum(int[] candidates, int target) {
 4         List<List<Integer>> LList = new ArrayList<List<Integer>>();  // 最終的結果集  5         if(candidates == null || candidates.length < 1 || target < 1 )
 6             return LList;
 7         Arrays.sort(candidates);  // 排序,使得不用對相同的結果集計算多次  8         List<Integer> list = new ArrayList<Integer>();  // 臨時結果保存  9         combinationSumCore(candidates,list, target, 0, LList);  // 核心函數 10         return LList;
11     }
12     public void combinationSumCore(int[] candidates,List<Integer> list, int target, int index, List<List<Integer>> LList)
13     {
14         for(int i = index; i < candidates.length; i++) 
15         {
16             if(candidates[i] == target)  // 等於,就加入結果集 17             {
18                 List<Integer> result = new ArrayList<Integer>();
19                 result.addAll(list);
20                 result.add(candidates[i]);
21                 LList.add(result);
22             }
23             else if(candidates[i] < target)  // 小於,就繼續遞歸 24             {
25                 List<Integer> result = new ArrayList<Integer>();
26                 result.addAll(list);
27                 result.add(candidates[i]);
28                 combinationSumCore(candidates, result, target - candidates[i], i, LList);  // 這邊i值不變,是因為當前值可以使用多次 29             }
30             else  // 大於,則后面的數字都大於,因此不可能出現在結果集中
31             {
32                 break;
33             }
34         }
35     }
36 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM