编程语言
首页 > 编程语言> > 算法:回溯十七 Combination Sum III挑选数组中规定个数元素的和为指定数

算法:回溯十七 Combination Sum III挑选数组中规定个数元素的和为指定数

作者:互联网

题目

地址:https://leetcode.com/problems/combination-sum-iii/

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Note:

All numbers will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:

Input: k = 3, n = 7
Output: [[1,2,4]]

Example 2:

Input: k = 3, n = 9
Output: [[1,2,6], [1,3,5], [2,3,4]]

DFS回溯解法

思路解析:

  1. 回溯的解法在于递归,递归要有出口条件if (sum == 0 && k == 0), 当满足条件则把集合添加到结果列表中。
  2. 回溯的就像人生选择,要么选择做这件事情list.add(i);, 要么选择不做这件事情list.remove(list.size() - 1);
  3. 记得要有行动,否则就是空谈,执行递归dfs(resultList, list, k - 1, sum - i, i + 1);
package backtracking;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

// https://leetcode.com/problems/combination-sum-iii/
public class CombinationSumIII {

  public static void main(String[] args) {
    int k = 3;
    int n = 9;
    CombinationSumIII obj = new CombinationSumIII();
    List<List<Integer>> resultList = obj.combinationSum3(k ,n);
    System.out.println(Arrays.toString(resultList.toArray()));
  }

  public List<List<Integer>> combinationSum3(int k, int n) {
    List<List<Integer>> resultList = new ArrayList<List<Integer>>();
    // dfs
    dfs(resultList, new ArrayList<Integer>(), k, n, 1);

    return resultList;
  }

  private void dfs(List<List<Integer>> resultList, List<Integer> list, int k, int sum, int start) {
    if (sum == 0 && k == 0) {
      resultList.add(new ArrayList<Integer>(list));
      return;
    }
    if (sum < 0) {
      return;
    }
    for (int i = start; i <= 9; i++) {
      // add num
      list.add(i);
      dfs(resultList, list, k - 1, sum - i, i + 1);

      // not add num
      list.remove(list.size() - 1);
    }
  }

}

代码下载

https://github.com/zgpeace/awesome-java-leetcode/blob/master/code/LeetCode/src/backtracking/CombinationSumIII.java

程序员易筋 发布了130 篇原创文章 · 获赞 12 · 访问量 2万+ 私信 关注

标签:java,Combination,int,List,Sum,list,resultList,III,sum
来源: https://blog.csdn.net/zgpeace/article/details/104058768