1. 程式人生 > >leecode-39. Combination Sum

leecode-39. Combination Sum

limited mit blank 列表 mov rep 空間復雜度 cas ()

1、問題描述:

Given a set of candidate numbers (C) (without duplicates) 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
    .
  • 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]
]

2、邊界條件:無
3、思路:先取一個數,然後與target比較;==則存貯,!=則繼續從所有數裏面選擇。

  從Level-N裏面選擇一個數,與目標比較,符合則存貯;不符合則再從所有數裏面挨個取,從而化為同樣的Level-N問題
形成遞歸。base case:1)與目標匹配;2)target - nums[i]<0,再減下去也是負數,這依賴於題目給的 全正數positive integers 條件

4、實現代碼:


class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> results = new ArrayList<>();
        //Arrays.sort(candidates);
        combinationSum(results, new ArrayList<Integer>(), candidates, target);
        
return results; } public void combinationSum(List<List<Integer>> results, List<Integer> cur, int[] candidates, int target) { if (0 == target) {
       /** Collections.sort(cur);//這裏排序會把原列表改變,所以上層在恢復現場時出錯。
if (!results.contains(cur)) {//去重 results.add(new ArrayList<Integer>(cur)); }
       **/

        ArrayList<Integer> result = new ArrayList<Integer>(cur);//先生成新的cur,然後進行排序
        Collections.sort(result); //
        if (!results.contains(result)) {
          results.add(result);
               return;

        }
        if (0 > target) {
            return;
        }
        for (int i = 0; i < candidates.length; i++) {
            cur.add(candidates[i]);
            combinationSum(results, cur, candidates, target - candidates[i]);
            cur.remove(cur.size() - 1);
        }
    }
}

5、時間復雜度:說不好; 空間復雜度:

6、題外知識:Arraylist排序:Collections靜態排序API,Collections的排序都是穩定的。Collections.sort(List<T> list)、和Collections.sort(List<T> list,Comparator<?super T> c);使用的排序是穩定的,主要是對list排序。

鏈接:http://blog.csdn.net/tuke_tuke/article/details/51100219 和 http://www.importnew.com/17211.html

 

leecode-39. Combination Sum