Created
November 16, 2013 14:10
-
-
Save tekkoc/7500527 to your computer and use it in GitHub Desktop.
dfs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import std.stdio; | |
import std.range; | |
import std.algorithm; | |
void main() | |
{ | |
auto target = 13; | |
auto ns = [1, 2, 4, 7]; | |
writeln(solve(target, ns)); | |
} | |
int sum(int[] ns) { | |
return reduce!("a + b")(0, ns); | |
} | |
int[] solve(int target, int[] ns) | |
{ | |
int[] f(int[] stock, int[] use) | |
{ | |
if (stock.empty) { | |
return (use.sum == target)? use : []; | |
} | |
int[] ret; | |
// stockの先頭を使うパターン | |
ret = f(stock[1..$], use ~ stock[0]); | |
if (!ret.empty) return ret; | |
// stockの先頭を使わないパターン | |
ret = f(stock[1..$], use); | |
if (!ret.empty) return ret; | |
return []; | |
} | |
return f(ns, []); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment