leetcode 40. Combination Sum II

来源:互联网 发布:网络与端口有何区别 编辑:程序博客网 时间:2024/06/04 06:27
import java.util.ArrayList;import java.util.Arrays;import java.util.List;//Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.////Each number in C 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.//For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8, //A solution set is: //[//  [1, 7],//  [1, 2, 5],//  [2, 6],//  [1, 1, 6]//]public class Solution { public static void main(String[] aargs){int target = 8;int[] candidates = {10,1,2,7,6,1,5};List<List<Integer>> result = combinationSum2(candidates, target);System.out.println(result);}    public static List<List<Integer>> combinationSum2(int[] candidates, int target) {    List<List<Integer>> result = new ArrayList<List<Integer>>();    Arrays.sort(candidates);    List<Integer> ans = new ArrayList<Integer>();    resolve(candidates, target, result, ans, -1);        return result;    }        public static void resolve(int[] candidates, int target, List<List<Integer>> result, List<Integer> ans, int pos) {    for(int i = pos+1;i<candidates.length;i++){//与上题很像,只是每次迭代从candidates中的下一个元素开始即可    if(target == candidates[i]){    ans.add(candidates[i]);    if(result.contains(ans)){//避免重复    ans.remove(ans.size()-1);    return;    }    result.add(new ArrayList<Integer>(ans));//new ArrayList<Iteger>的作用是使结果列表的值不随之后ans的改变而改变    ans.remove(ans.size()-1);    return;    }    if(target > candidates[i]){    ans.add(candidates[i]);    resolve(candidates, target-candidates[i], result, ans, i);//candidates,减去当前元素后的target,结果列表,当前整形元素列表,当前检索到了什么位置    ans.remove(ans.size()-1);    }else{    return;    }    }    }    }

0 0
原创粉丝点击