LeetCode039数组总和

20 阅读1分钟

题目:

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的数字可以无限制重复被选取。

说明:

  • 所有数字(包括 target)都是正整数。
  • 解集不能包含重复的组合。

示例 1:

  • 输入:candidates = [2,3,6,7], target = 7,
  • 所求解集为:
    [
    [7],
    [2,2,3]
    ]

示例 2:

  • 输入:candidates = [2,3,5], target = 8,
  • 所求解集为:
    [
    [2,2,2,2],
    [2,3,3],
    [3,5]
    ]

java:

public class Leetcode039 {

    public static List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        //先进行排序.
        Arrays.sort(candidates);
        backtrack(res, new ArrayList<>(), candidates, target, 0, 0);
        return res;
    }

    private static void backtrack(List<List<Integer>> res, List<Integer> path, int[] candidates, int target, int sum, int idx) {
        //找到满足条件的结果.
        if (sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = idx; i < candidates.length; i++) {
            if (sum + candidates[i] > target) break;
            path.add(candidates[i]);
            backtrack(res, path, candidates, target, sum + candidates[i], i);
            path.remove(path.size() - 1);
        }
    }

    public static void main(String[] args) {
        int[] candidates = {2,3,6,7};
        int target = 7;
        System.out.println(combinationSum(candidates, target));
    }
}

Go:

package LeetCode

import (
	"sort"
)

var (
	resSort  [][]int
	pathSort []int
)

func CombinationSum(candidates []int, target int) [][]int {
	resSort, pathSort = make([][]int, 0), make([]int, len(candidates))
	//排序.
	sort.Ints(candidates)
	dfsSort(candidates, 0, target)
	return resSort
}

func dfsSort(candidates []int, start int, target int) {
	if target == 0 {
		tmp := make([]int, len(pathSort))
		copy(tmp, pathSort)
		resSort = append(resSort, tmp)
		removeZero(resSort)
		return
	}
	for i := start; i < len(candidates); i++ {
		if candidates[i] > target {
			break
		}
		pathSort = append(pathSort, candidates[i])
		dfsSort(candidates, i, target-candidates[i])
		pathSort = pathSort[:len(pathSort)-1]
	}
}

func removeZero(array [][]int) [][]int {
	for i := 0; i < len(array); i++ {
		slice := array[i]
		num := make([]int, 0)
		for _, value := range slice {
			if value != 0 {
				num = append(num, value)
			}
		}
		array[i] = num
	}
	return array
}

仰天大笑出门去.





如果大家喜欢我的分享的话.可以关注我的微信公众号

念何架构之路