leetcode Combination Sum III-回溯|递归

来源:互联网 发布:终极三国 知乎 编辑:程序博客网 时间:2024/04/30 12:20
原题链接:Combination Sum III

【思路】-递归实现

用回溯算法实现。最外层循环从1到9逐一往中间集中添加一个数,然后递归,如果数量凑足 k 个,并且它们的和刚好为 n,那么就将中间集添加到结果集中。下一次循环时,将添加刚刚添加到中间集中的那个数移除,进行下一次循环:

public class Solution {    public List<List<Integer>> combinationSum3(int k, int n) {        List<List<Integer>> res = new ArrayList<List<Integer>>();        List<Integer> temp = new ArrayList<Integer>();        dfs(res, temp, 1, k, n);        return res;    }    private void dfs(List<List<Integer>> res, List<Integer> temp, int i, int k, int n) {        if (k == 0 && n == 0)                res.add(new ArrayList<Integer>(temp));        for (; i <= 9 && n > 0; i++) {            temp.add(i);            dfs(res, temp, i+1, k-1, n-i);            temp.remove(temp.size()-1);        }    }}
18 / 18 test cases passed. Runtime: 1 ms  Your runtime beats 61.86% of javasubmissions.

1 0
原创粉丝点击