zoukankan      html  css  js  c++  java
  • 部分和问题

    给定整数 a1、a2、…、an,判断是否可以从中选出若干数,使它们的和恰好为 k。

    限制条件

     1 ≤ n ≤ 20
     108 ≤ ai ≤ 108
     108 ≤ k ≤ 108

    输入

    n=4
    a={1,2,4,7}
    k=13

    输出

    Yes
    提示:另一组输入k=15输出为no
    从a1开始按顺序决定每个数加或不加,在全部n个数都决定后再判断它们的和是不是k即可。因为状态数是2n+1,所以复杂度是O(2n)。
    **深度优先搜索从最开始的状态出发,遍历所有可以到达的状态。由此可以对所有的状态进行操作,或者列举出所有的状态。 **

    java实现

    import java.util.Scanner;
    
    public class Main {
    	static int arr[];
    	static int n,a;
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Scanner scn = new Scanner(System.in);
    		n = scn.nextInt();
    		arr = new int[n];
    		for(int i=0;i<n;i++) {
    			arr[i]=scn.nextInt();
    		}
    		a = scn.nextInt();
    		System.out.println(f(0,0));
    	}
    	
    	public static boolean f(int m,int sum) {
    		if(n==m) {
    			return a==sum;
    		}
    		//不加
    		if(f(m+1,sum)) {
    			return true;
    		}
    		//加
    		if(f(m+1,sum+arr[m])) {
    			return true;
    		}
    		return false;
    	}
    }
    
  • 相关阅读:
    https协议介绍
    最详尽的fidder抓取https请求
    最详尽的datagrip使用
    datagrip安装与破解
    二叉树
    使用nexus搭建maven私库
    markdown利器-小书匠
    java开发-flyway
    .NetCore 入门
    .Net Core 实体生成器
  • 原文地址:https://www.cnblogs.com/zhangguangxiang/p/14232569.html
Copyright © 2011-2022 走看看