combination sum 3

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

/**
 * 给定一个数字x,要求使用k个数字求和可以得到x,数字从1-9中选择,不能重复。
 *
 * 实现一个函数,在输入 x,k 时,输出所有可以求和得到x的列表
 *
 *  例子:
 *
 * 输入:k= 3, x = 9
 *
 * 输出: [[1,2,6], [1,3,5], [2,3,4]]
 */
public class CombinationSum3 {
    public static void main(String[] args){
        List<List<Integer>> list = combinationSum(3,9);
        for(int i=0;i<list.size();i++){
            for (int j=0;j<list.get(i).size();j++){
                System.out.print(list.get(i).get(j));
            }
            System.out.println();
        }
    }
    public static List<List<Integer>> combinationSum(int k, int x){
        List<List<Integer>> list = new ArrayList<>();
        helper(list,new ArrayList<Integer>(),k,x,1);
        return list;
    }
    private static void helper(List<List<Integer>> list, ArrayList<Integer> tempList,int k, int x, int start) {
        if(tempList.size()>k){
            return ;
        }
        if(tempList.size() == k && x == 0){
            list.add(new ArrayList<>(tempList));
            return ;
        }
        for(int i=start;i<=9;i++){
            tempList.add(i);
            helper(list,tempList,k,x-i,i+1);
            tempList.remove(tempList.size() -1 );
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值