博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Combination Sum III
阅读量:2341 次
发布时间:2019-05-10

本文共 1254 字,大约阅读时间需要 4 分钟。

思路回溯算法

public class Solution {
public List
> combinationSum3(int k, int n) { List
> totalResult=new ArrayList
>(); int record[]={ 0,0,0,0,0,0,0,0,0,0}; process(k, n, record, 1, 0, totalResult); return totalResult; } public void process(int k,int n,int record[],int i,int currentsum,List
> totalResult) { if(i>9) { return; } k--; record[i]=1; if(currentsum+i==n&&k==0) { List
result=new ArrayList
(); for(int j=0;j<10;j++) { if(record[j]==1) { result.add(j); } } totalResult.add(result); record[i]=0; return; } currentsum+=i; if(currentsum
0) { process(k, n, record, i+1, currentsum, totalResult); } record[i]=0; currentsum-=i; k++; process(k, n, record, i+1, currentsum, totalResult); return; }}

别人的算法

public class Solution {
public List
> combinationSum3(int k, int n) { List
> res=new ArrayList
>(); recur(new ArrayList
(),res,n,1,k); return res; } public void recur(List
temp,List
> res, int tar,int k,int count){ if(tar==0&&count==0){ res.add(temp); return; } if(count==0||tar<=0)return; for(int i=k;i<=9;i++){ temp.add(i); recur(new ArrayList
(temp),res,tar-i,i+1,count-1); temp.remove(temp.size()-1); } }}

转载地址:http://hbuvb.baihongyu.com/

你可能感兴趣的文章
特征向量的欧式距离与余弦距离——推荐算法
查看>>
cJSON源码分析3-核心解析算法
查看>>
如何正确使用C中的可变参数
查看>>
SDL2.0-简介
查看>>
SDL2.0-播放YUV文件
查看>>
leetcode 1.TwoSum--hashmap
查看>>
leetcode 14. Longest Common Prefix
查看>>
leetcode 26. Remove Duplicates from Sorted Array
查看>>
leetcode 27. Remove Element
查看>>
leetcode 66. Plus One
查看>>
leetcode 111. Minimum Depth of Binary Tree
查看>>
leetcode 257. Binary Tree Paths
查看>>
poj1611-并查集
查看>>
Trie树(字典树)
查看>>
大数运算-模拟
查看>>
腾讯2017暑假实习笔试题-字符串编码
查看>>
腾讯2017暑假笔试题-查找二叉树的根
查看>>
迭代器概念及traits编程技法.md
查看>>
Linux安装cmake
查看>>
SRS源码分析-协程相关类
查看>>