日期:2014-05-17 浏览次数:20996 次
import java.util.*;
public class Test {
public static void main(String[] args) throws Throwable {
String s = "25482";
for (int i=0; i<s.length(); i++) {
System.out.printf("-------- %d div test --------\n", i+1);
for (List<String> l : div(s, i+1)) {
System.out.println(l);
}
}
}
public static List<List<String>> div(String src, int count) {
List<List<String>> result = new ArrayList<List<String>>();
if (src==null || src.length()==0 || count < 1 || count > src.length()) {
return result;
}
if (count == 1) {
List<String> list = new ArrayList<String>();
list.add(src);
result.add(list);
return result;
}
for (int i=0; i<src.length(); i++) {
String s = src.substring(0, i+1);
if (i+1 < src.length()) {
List<List<String>> t = div(src.substring(i+1), count-1);
for (List<String> l : t) {
l.add(0, s);
result.add(l);
}
}
}
return result;
}
}
------解决方案--------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string s = "25482";
int n = 2;
var data = Enumerable.Range(1, s.Length - 1);
IEnumerable<int[]> query = data.Select(x => new int[] { x });
for (int i = 1; i < n; i++)
{
query = query.SelectMany(x => data.Select(y => x.Concat(new int[] { y }).ToArray()));
}
query = query
.Select(x => x.OrderBy(y => y).Distinct().ToArray())
.Where(x => x.Count() == n - 1)
.OrderByDescending(x => string.Join(",", x))
.GroupBy(x => string.Join(",", x))
.Select(x => x.First())
.Select(x => new int[] { 0 }.Concat(x).ToArray());
foreach (var item in query)
{
Console.WriteLine(string.Join("", s.Select((x, i) => item.Contains(i) ? "x" + x : x.ToString())));
}
}
}
}