Skip to content

Instantly share code, notes, and snippets.

@tekkoc
Created November 16, 2013 14:10
Show Gist options
  • Save tekkoc/7500527 to your computer and use it in GitHub Desktop.
Save tekkoc/7500527 to your computer and use it in GitHub Desktop.
dfs
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