Array sum is K - DP

本文介绍了一种使用动态规划解决子集和问题的方法。该方法通过构建二维布尔数组来记录数组中的元素是否能组合成特定的目标和。文章提供了详细的算法步骤及其实现代码。

求出一个数组arr中有没有那几个数加起来等于S,有,返回true 没有返回false。

分析:

eg:arr={2,4,6,3}  S=10;

动态规划可以这么理解:1、很多个重叠子问题 2、选或者不选的问题

对于数组中的每一个数,比如例子中的3,如果选择,则需要3之前的数可以组成S-3=7

按下标i表示:

                    如果选:f(i,S)=f(i-1,S-arr[i]);

                    如果不选:f(i)=f(i-1,S)

再考虑问题的出口:当数组只有一个元素,此时返回arr[0]==S;

当S=0,即f(i,S)中S为0,说明在i的后面的数组中已经有加起来等于S的数,则返回true,

如果arr[i]>S ,则直接计算f(i-1,S)即可。

动态规划可以用递归的方式完成,但复杂度为O(2^n),因为它是由大到小的推,比如要算f(i),要算f(i-1),而动态规划是从小到大,先计算f(i),再计算f(i+1),把每次的结果存储下来,最后复杂度变为O(n)。

下面是代码实现:rec_subSet是递归实现,dp_subSet是动态规划实现。

package test;


public class Main {
	
	public static boolean rec_subSet(int[] arr,int i,int S){
		if(S==0)
			return true;
		if(i==0)
			return arr[i]==S;
		if(arr[i]>S){
			return rec_subSet(arr,i-1, S);
		}
		return rec_subSet(arr, i-1, S-arr[i])||rec_subSet(arr, i-1, S);
	}
	
	public static void dp_subSet(int[] arr,int S) {
boolean[][] subSet = new boolean[arr.length][S+1];
    	
    	for(int i = 0; i <= arr.length-1; i++){
    		subSet[i][0] = true;
    	}
    	
    	for(int i = 0; i <= S; i++){
    		subSet[0][i] = false;
    		if(i==arr[0])
    			subSet[0][arr[0]] = true;
    	}
    	
    	for(int i = 1; i <= arr.length-1;i++){
    		for(int s = 1;s<=S;s++){
    			if(arr[i]>s)
    				subSet[i][s] = subSet[i-1][s];
    			else {
					subSet[i][s] = (subSet[i-1][s-arr[i]]) || (subSet[i-1][s]);
				}
    		}
    	}
    	System.out.println(subSet[5][S]);
	}
    public static void main(String[] args) {
    	
    	int[] arr = {3,34,4,12,5,2};
    	int S = 9;
    	dp_subSet(arr, S);
    	System.out.println(rec_subSet(arr,arr.length-1,S));
    }
     
}


Traceback (most recent call last): File "<string>", line 1, in <module> File "E:\xiazai\miniconda\envs\opencv-dp\lib\multiprocessing\spawn.py", line 116, in spawn_main exitcode = _main(fd, parent_sentinel) File "E:\xiazai\miniconda\envs\opencv-dp\lib\multiprocessing\spawn.py", line 125, in _main prepare(preparation_data) File "E:\xiazai\miniconda\envs\opencv-dp\lib\multiprocessing\spawn.py", line 236, in prepare _fixup_main_from_path(data['init_main_from_path']) File "E:\xiazai\miniconda\envs\opencv-dp\lib\multiprocessing\spawn.py", line 287, in _fixup_main_from_path main_content = runpy.run_path(main_path, File "E:\xiazai\miniconda\envs\opencv-dp\lib\runpy.py", line 288, in run_path return _run_module_code(code, init_globals, run_name, File "E:\xiazai\miniconda\envs\opencv-dp\lib\runpy.py", line 97, in _run_module_code _run_code(code, mod_globals, init_globals, File "E:\xiazai\miniconda\envs\opencv-dp\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "D:\machine vision\opencv-cuda\main.py", line 210, in <module> train_loss_1, val_loss_1 = train_model( File "D:\machine vision\opencv-cuda\main.py", line 183, in train_model for images, labels in train_loader: File "E:\xiazai\miniconda\envs\opencv-dp\lib\site-packages\torch\utils\data\dataloader.py", line 493, in __iter__ return self._get_iterator() File "E:\xiazai\miniconda\envs\opencv-dp\lib\site-packages\torch\utils\data\dataloader.py", line 424, in _get_iterator return _MultiProcessingDataLoaderIter(self) File "E:\xiazai\miniconda\envs\opencv-dp\lib\site-packages\torch\utils\data\dataloader.py", line 1171, in __init__ w.start() File "E:\xiazai\miniconda\envs\opencv-dp\lib\multiprocessing\process.py", line 121, in start self._popen = self._Popen(self) File "E:\xiazai\miniconda\envs\opencv-dp\lib\multiprocessing\context.py", line 224, in _Popen return _default_context.get_context().Process._Popen(process_obj) File "E:\xiazai\miniconda\envs\opencv-dp\lib\multiprocessing\context.py", line 327, in _Popen return Popen(process_obj) File "E:\xiazai\miniconda\envs\opencv-dp\lib\multiprocessing\popen_spawn_win32.py", line 45, in __init__ prep_data = spawn.get_preparation_data(process_obj._name) File "E:\xiazai\miniconda\envs\opencv-dp\lib\multiprocessing\spawn.py", line 154, in get_preparation_data _check_not_importing_main() File "E:\xiazai\miniconda\envs\opencv-dp\lib\multiprocessing\spawn.py", line 134, in _check_not_importing_main raise RuntimeError(''' RuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase. This probably means that you are not using fork to start your child processes and you have forgotten to use the proper idiom in the main module: if __name__ == '__main__': freeze_support() ... The "freeze_support()" line can be omitted if the program is not going to be frozen to produce an executable.
11-09
e.f90 C:\practice\practice.f90(173) : Error: A kind type parameter must be a compile-time constant. [DP] real(dp), intent(in) :: xx(mm) ---------------------^ C:\practice\practice.f90(174) : Error: A kind type parameter must be a compile-time constant. [DP] real(dp), intent(out) :: ff ---------------------^ C:\practice\practice.f90(175) : Error: A kind type parameter must be a compile-time constant. [DP] real(dp), intent(out) :: gg(mm) ---------------------^ C:\practice\practice.f90(238) : Error: A kind type parameter must be a compile-time constant. [DP] real(dp), intent(in) :: xx(mm) ---------------------^ C:\practice\practice.f90(239) : Error: A kind type parameter must be a compile-time constant. [DP] real(dp), intent(out) :: ff ---------------------^ C:\practice\practice.f90(240) : Error: A kind type parameter must be a compile-time constant. [DP] real(dp), intent(out) :: gg(mm) ---------------------^ C:\practice\practice.f90(186) : Error: The type of the actual argument differs from the type of the dummy argument. [X] call func(m, x, f, g, charge_arr) ---------------------^ C:\practice\practice.f90(186) : Error: The type of the actual argument differs from the type of the dummy argument. [F] call func(m, x, f, g, charge_arr) ------------------------^ C:\practice\practice.f90(186) : Error: The type of the actual argument differs from the type of the dummy argument. [G] call func(m, x, f, g, charge_arr) ---------------------------^ C:\practice\practice.f90(187) : Error: This name does not have a type, and must have an explicit type. [NORM2] grad_tol = norm2(g) -------------------^ C:\practice\practice.f90(204) : Error: The type of the actual argument differs from the type of the dummy argument. [X] call func(m, x, f, g_new, charge_arr) -------------------------^ C:\practice\practice.f90(204) : Error: The type of the actual argument differs from the type of the dummy argument. [F] call func(m, x, f, g_new, charge_arr) ----------------------------^ C:\practice\practice.f90(204) : Error: The type of the actual argument differs from the type of the dummy argument. [G_NEW] call func(m, x, f, g_new, charge_arr) -------------------------------^ C:\practice\practice.f90(249) : Error: The type of the actual argument differs from the type of the dummy argument. [X_OUT] call func(m, x_out, f_out, g, charge_arr) -------------------------^ C:\practice\practice.f90(249) : Error: The type of the actual argument differs from the type of the dummy argument. [F_OUT] call func(m, x_out, f_out, g, charge_arr) --------------------------------^ C:\practice\practice.f90(249) : Error: The type of the actual argument differs from the type of the dummy argument. [G] call func(m, x_out, f_out, g, charge_arr) ---------------------------------------^ C:\practice\practice.f90(249) : Error: There is an assignment to a dummy symbol with the explicit INTENT(IN) attribute [G] call func(m, x_out, f_out, g, charge_arr) ---------------------------------------^ C:\practice\practice.f90(259) : Error: The type of the actual argument differs from the type of the dummy argument. [X_OUT] call func(m, x_out, f_out, g, charge_arr) ---------------------^ C:\practice\practice.f90(259) : Error: The type of the actual argument differs from the type of the dummy argument. [F_OUT] call func(m, x_out, f_out, g, charge_arr) ----------------------------^ C:\practice\practice.f90(259) : Error: The type of the actual argument differs from the type of the dummy argument. [G] call func(m, x_out, f_out, g, charge_arr) -----------------------------------^ C:\practice\practice.f90(259) : Error: There is an assignment to a dummy symbol with the explicit INTENT(IN) attribute [G] call func(m, x_out, f_out, g, charge_arr) -----------------------------------^ C:\practice\practice.f90(265) : Error: The shapes of the array expressions do not conform. [X] x = [1.0_dp, 1.0_dp, 0.5_dp, 0.0_dp, 0.0_dp, & --------^ C:\practice\practice.f90(297) : Error: Error in opening the Library module file. [POTENTIAL_MOD] use potential_mod --------^ C:\practice\practice.f90(301) : Error: A kind type parameter must be a compile-time constant. [DP] real(dp) :: x(ndim) ---------^ C:\practice\practice.f90(302) : Error: A kind type parameter must be a compile-time constant. [DP] real(dp) :: f, g(ndim) ---------^ C:\practice\practice.f90(307) : Error: Keyword arguments are invalid without an explicit interface. [TOL] call bfgs(ndim, x, f, g, tol=1.0e-6_dp, max_iter=1000, converged=converged, & -----------------------------^ C:\practice\practice.f90(307) : Error: This name does not have a type, and must have an explicit type. [DP] call bfgs(ndim, x, f, g, tol=1.0e-6_dp, max_iter=1000, converged=converged, & ---------------------------------------^ C:\practice\practice.f90(307) : Error: A kind-param must be a digit-string or a scalar-int-constant-name [DP] call bfgs(ndim, x, f, g, tol=1.0e-6_dp, max_iter=1000, converged=converged, & ---------------------------------------^ C:\practice\practice.f90(307) : Error: Keyword arguments are invalid without an explicit interface. [MAX_ITER] call bfgs(ndim, x, f, g, tol=1.0e-6_dp, max_iter=1000, converged=converged, & --------------------------------------------^ C:\practice\practice.f90(307) : Error: Keyword arguments are invalid without an explicit interface. [CONVERGED] call bfgs(ndim, x, f, g, tol=1.0e-6_dp, max_iter=1000, converged=converged, & -----------------------------------------------------------^ (319) : Severe: Too many errors, exiting Error executing df.exe. practice.exe - 30 error(s), 0 warning(s)
11-02
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值