题解 | #加起来和为目标值的组合#

加起来和为目标值的组合

http://www.nowcoder.com/practice/75e6cd5b85ab41c6a7c43359a74e869a

import java.util.*;

public class Solution {

ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) {
    Arrays.sort(num);
    combinationSum(num, new ArrayList<>(), 0, target);
    return result;
}

public void combinationSum(int[] sum, ArrayList<Integer> res, int startIdx, int target) {

    if(target == 0) {
        result.add(new ArrayList<>(res));
        return;
    }

    if(startIdx >= sum.length || sum[startIdx] > target) {
        return;
    } 

    for(int i = startIdx; i < sum.length; i ++) {
        res.add(sum[i]);
        combinationSum(sum, res, i+1, target - sum[i]);
        res.remove(res.size()-1);
        while(i < sum.length-1 && sum[i] == sum[i+1]) {
            i++;
        }
    }
}

}

全部评论

相关推荐

评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务